Kotlin and Java API for generating Kotlin source files (.kt) with type-safe, fluent builder patterns
npx @tessl/cli install tessl/maven-com-squareup--kotlinpoet@2.2.00
# KotlinPoet
1
2
KotlinPoet is a comprehensive Kotlin and Java API for generating Kotlin source files (.kt) programmatically. It provides type-safe, fluent builder patterns for creating well-formatted Kotlin code, supporting all modern Kotlin language constructs including classes, functions, properties, type aliases, and annotations. As a multiplatform library supporting JVM, JavaScript, and WebAssembly targets, KotlinPoet is the go-to solution for code generation in build tools, annotation processors, and development utilities.
3
4
## Package Information
5
6
- **Package Name**: kotlinpoet
7
- **Package Type**: maven
8
- **Language**: Kotlin (Multiplatform: JVM, JS, WebAssembly)
9
- **Installation**:
10
- **Gradle**: `implementation("com.squareup:kotlinpoet:2.2.0")`
11
- **Maven**:
12
```xml
13
<dependency>
14
<groupId>com.squareup</groupId>
15
<artifactId>kotlinpoet</artifactId>
16
<version>2.2.0</version>
17
</dependency>
18
```
19
20
## Core Imports
21
22
```kotlin
23
import com.squareup.kotlinpoet.*
24
```
25
26
Common specific imports:
27
28
```kotlin
29
import com.squareup.kotlinpoet.FileSpec
30
import com.squareup.kotlinpoet.TypeSpec
31
import com.squareup.kotlinpoet.FunSpec
32
import com.squareup.kotlinpoet.PropertySpec
33
import com.squareup.kotlinpoet.ClassName
34
import com.squareup.kotlinpoet.CodeBlock
35
```
36
37
For JVM-specific annotations:
38
39
```kotlin
40
import com.squareup.kotlinpoet.jvm.JvmAnnotations
41
```
42
43
## Basic Usage
44
45
```kotlin
46
import com.squareup.kotlinpoet.*
47
48
// Create a simple class with a function
49
val greeterClass = TypeSpec.classBuilder("Greeter")
50
.addProperty(
51
PropertySpec.builder("name", String::class)
52
.initializer("%S", "World")
53
.build()
54
)
55
.addFunction(
56
FunSpec.builder("greet")
57
.returns(String::class)
58
.addStatement("return %S + name", "Hello, ")
59
.build()
60
)
61
.build()
62
63
// Create a file containing the class
64
val file = FileSpec.builder("com.example", "Greeter")
65
.addType(greeterClass)
66
.build()
67
68
// Output the generated code
69
file.writeTo(System.out)
70
71
/* Generated output:
72
package com.example
73
74
import kotlin.String
75
76
class Greeter {
77
val name: String = "World"
78
79
fun greet(): String = "Hello, " + name
80
}
81
*/
82
```
83
84
## Architecture
85
86
KotlinPoet is built around several key architectural components:
87
88
- **Specification Builders**: Core classes (`FileSpec`, `TypeSpec`, `FunSpec`, `PropertySpec`) using the Builder pattern for constructing code elements
89
- **Type System**: Complete representation of Kotlin's type system (`TypeName`, `ClassName`, `ParameterizedTypeName`) with nullability and annotation support
90
- **Code Generation**: `CodeBlock` for template-based code fragment generation with placeholder substitution
91
- **Multiplatform Design**: Common API with platform-specific implementations for JVM, JS, and WebAssembly
92
- **Utility Layer**: `NameAllocator` for identifier management, `KModifier`/`KOperator` enums for language constructs
93
94
## Capabilities
95
96
### File and Type Generation
97
98
Core functionality for creating Kotlin files and type declarations including classes, interfaces, objects, and annotation classes. This forms the foundation of all code generation workflows.
99
100
```kotlin { .api }
101
// File specification
102
class FileSpec private constructor() {
103
companion object {
104
fun builder(packageName: String, fileName: String): Builder
105
fun builder(className: ClassName): Builder
106
fun builder(memberName: MemberName): Builder
107
fun get(packageName: String, typeSpec: TypeSpec): FileSpec
108
fun scriptBuilder(fileName: String, packageName: String = ""): Builder
109
}
110
fun writeTo(out: Appendable)
111
fun writeTo(directory: Path)
112
fun toJavaFileObject(): JavaFileObject
113
fun toBuilder(packageName: String = this.packageName, name: String = this.name): Builder
114
}
115
116
// Type specification
117
class TypeSpec private constructor() {
118
companion object {
119
fun classBuilder(name: String): Builder
120
fun classBuilder(className: ClassName): Builder
121
fun interfaceBuilder(name: String): Builder
122
fun interfaceBuilder(className: ClassName): Builder
123
fun funInterfaceBuilder(name: String): Builder
124
fun funInterfaceBuilder(className: ClassName): Builder
125
fun objectBuilder(name: String): Builder
126
fun objectBuilder(className: ClassName): Builder
127
fun annotationBuilder(name: String): Builder
128
fun annotationBuilder(className: ClassName): Builder
129
fun enumBuilder(name: String): Builder
130
fun enumBuilder(className: ClassName): Builder
131
fun anonymousClassBuilder(): Builder
132
fun companionObjectBuilder(name: String? = null): Builder
133
}
134
fun toBuilder(kind: Kind = this.kind, name: String? = this.name): Builder
135
}
136
```
137
138
[File and Type Generation](./file-and-type-generation.md)
139
140
### Function and Property Generation
141
142
Comprehensive support for generating functions, constructors, properties, and parameters with full Kotlin language feature support including modifiers, annotations, and documentation.
143
144
```kotlin { .api }
145
// Function specification
146
class FunSpec private constructor() {
147
companion object {
148
fun builder(name: String): Builder
149
fun builder(memberName: MemberName): Builder
150
fun constructorBuilder(): Builder
151
fun getterBuilder(): Builder
152
fun setterBuilder(): Builder
153
}
154
}
155
156
// Property specification
157
class PropertySpec private constructor() {
158
companion object {
159
fun builder(name: String, type: TypeName, vararg modifiers: KModifier): Builder
160
fun varBuilder(name: String, type: TypeName, vararg modifiers: KModifier): Builder
161
}
162
}
163
164
// Parameter specification
165
class ParameterSpec private constructor() {
166
companion object {
167
fun builder(name: String, type: TypeName, vararg modifiers: KModifier): Builder
168
fun unnamed(type: TypeName): ParameterSpec
169
}
170
}
171
```
172
173
[Function and Property Generation](./function-and-property-generation.md)
174
175
### Type System
176
177
Complete representation of Kotlin's type system including classes, generics, wildcards, lambda types, and type variables. Provides type-safe APIs for working with complex type hierarchies and generic type parameters.
178
179
```kotlin { .api }
180
// Base type representation
181
abstract class TypeName {
182
val isNullable: Boolean
183
val annotations: List<AnnotationSpec>
184
fun copy(nullable: Boolean = this.isNullable, annotations: List<AnnotationSpec> = this.annotations): TypeName
185
}
186
187
// Class and interface types
188
class ClassName : TypeName {
189
companion object {
190
fun get(packageName: String, simpleName: String, vararg simpleNames: String): ClassName
191
fun get(clazz: Class<*>): ClassName
192
fun get(klass: KClass<*>): ClassName
193
fun bestGuess(classNameString: String): ClassName
194
}
195
fun parameterizedBy(vararg typeArguments: TypeName): ParameterizedTypeName
196
}
197
198
// Parameterized (generic) types
199
class ParameterizedTypeName : TypeName {
200
val rawType: ClassName
201
val typeArguments: List<TypeName>
202
companion object {
203
fun get(rawType: ClassName, vararg typeArguments: TypeName): ParameterizedTypeName
204
}
205
}
206
```
207
208
[Type System](./type-system.md)
209
210
### Code Generation and Templates
211
212
Template-based code generation with placeholder substitution, supporting complex code structures and maintaining proper formatting and imports.
213
214
```kotlin { .api }
215
// Code block with template support
216
class CodeBlock private constructor() {
217
companion object {
218
fun of(format: String, vararg args: Any?): CodeBlock
219
fun builder(): Builder
220
fun join(codeBlocks: Iterable<CodeBlock>, separator: String = ", "): CodeBlock
221
}
222
}
223
224
// Member reference for imports and qualified names
225
class MemberName {
226
companion object {
227
fun get(enclosingClassName: ClassName, simpleName: String): MemberName
228
fun get(packageName: String, simpleName: String): MemberName
229
fun get(clazz: Class<*>, simpleName: String): MemberName
230
fun get(klass: KClass<*>, simpleName: String): MemberName
231
}
232
}
233
```
234
235
[Code Generation and Templates](./code-generation.md)
236
237
### Annotations and Metadata
238
239
Complete support for Kotlin and Java annotations including annotation specifications, JVM-specific annotations, and metadata generation for annotation processors.
240
241
```kotlin { .api }
242
// Annotation specification
243
class AnnotationSpec private constructor() {
244
companion object {
245
fun builder(type: ClassName): Builder
246
fun builder(type: Class<*>): Builder
247
fun builder(type: KClass<*>): Builder
248
}
249
}
250
251
// Type alias specification
252
class TypeAliasSpec private constructor() {
253
companion object {
254
fun builder(name: String, type: TypeName): Builder
255
}
256
}
257
```
258
259
[Annotations and Metadata](./annotations-and-metadata.md)
260
261
### Utilities and Language Support
262
263
Essential utilities for name allocation, modifier management, and platform-specific functionality across JVM, JavaScript, and WebAssembly targets.
264
265
```kotlin { .api }
266
// Name collision avoidance
267
class NameAllocator {
268
fun newName(suggestion: String, tag: Any? = null): String
269
fun get(tag: Any): String
270
fun clone(): NameAllocator
271
}
272
273
// Kotlin modifiers
274
enum class KModifier {
275
PUBLIC, PROTECTED, PRIVATE, INTERNAL,
276
EXPECT, ACTUAL, FINAL, OPEN, ABSTRACT, SEALED,
277
CONST, EXTERNAL, OVERRIDE, LATEINIT, TAILREC,
278
VARARG, SUSPEND, INNER, ENUM, ANNOTATION, FUN,
279
COMPANION, INLINE, VALUE, INFIX, OPERATOR, DATA,
280
CROSSINLINE, NOINLINE, REIFIED
281
}
282
283
// Kotlin operators
284
enum class KOperator {
285
UNARY_PLUS, PLUS, UNARY_MINUS, MINUS, TIMES, DIV, REM,
286
PLUS_ASSIGN, MINUS_ASSIGN, TIMES_ASSIGN, DIV_ASSIGN, REM_ASSIGN,
287
INC, DEC, EQUALS, NOT_EQUALS, NOT,
288
RANGE_TO, CONTAINS, NOT_CONTAINS,
289
GT, LT, GE, LE, ITERATOR
290
}
291
```
292
293
[Utilities and Language Support](./utilities.md)
294
295
## Type Definitions
296
297
### Common Built-in Types
298
299
```kotlin { .api }
300
// Core types
301
val ANY: ClassName
302
val UNIT: ClassName
303
val NOTHING: ClassName
304
val DYNAMIC: Dynamic
305
306
// Primitive types
307
val BOOLEAN: ClassName
308
val BYTE: ClassName
309
val SHORT: ClassName
310
val INT: ClassName
311
val LONG: ClassName
312
val CHAR: ClassName
313
val FLOAT: ClassName
314
val DOUBLE: ClassName
315
val STRING: ClassName
316
val NUMBER: ClassName
317
318
// Character and comparison types
319
val CHAR_SEQUENCE: ClassName
320
val COMPARABLE: ClassName
321
val THROWABLE: ClassName
322
val ANNOTATION: ClassName
323
val ENUM: ClassName
324
325
// Unsigned types
326
val U_BYTE: ClassName
327
val U_SHORT: ClassName
328
val U_INT: ClassName
329
val U_LONG: ClassName
330
331
// Collection types
332
val ITERABLE: ClassName
333
val COLLECTION: ClassName
334
val LIST: ClassName
335
val SET: ClassName
336
val MAP: ClassName
337
val MAP_ENTRY: ClassName
338
val MUTABLE_ITERABLE: ClassName
339
val MUTABLE_COLLECTION: ClassName
340
val MUTABLE_LIST: ClassName
341
val MUTABLE_SET: ClassName
342
val MUTABLE_MAP: ClassName
343
val MUTABLE_MAP_ENTRY: ClassName
344
345
// Array types
346
val ARRAY: ClassName
347
val BOOLEAN_ARRAY: ClassName
348
val BYTE_ARRAY: ClassName
349
val CHAR_ARRAY: ClassName
350
val SHORT_ARRAY: ClassName
351
val INT_ARRAY: ClassName
352
val LONG_ARRAY: ClassName
353
val FLOAT_ARRAY: ClassName
354
val DOUBLE_ARRAY: ClassName
355
356
// Unsigned array types
357
val U_BYTE_ARRAY: ClassName
358
val U_SHORT_ARRAY: ClassName
359
val U_INT_ARRAY: ClassName
360
val U_LONG_ARRAY: ClassName
361
362
// Wildcard type
363
val STAR: WildcardTypeName
364
```
365
366
### Core Interfaces
367
368
```kotlin { .api }
369
// Tagging support for builders
370
interface Taggable {
371
val tags: Map<KClass<*>, Any>
372
}
373
374
// Documentation support
375
interface Documentable {
376
val kdoc: CodeBlock
377
}
378
379
// Annotation processing support
380
interface OriginatingElementsHolder {
381
val originatingElements: List<Element>
382
}
383
```