0
# Function and Property Generation
1
2
Comprehensive support for generating functions, constructors, properties, and parameters with full Kotlin language feature support including modifiers, annotations, and documentation.
3
4
## Capabilities
5
6
### Function Specification
7
8
Creates function declarations including regular functions, constructors, getters, setters, and operator functions with full Kotlin language support.
9
10
```kotlin { .api }
11
/**
12
* Specification for generating functions and constructors
13
*/
14
class FunSpec private constructor() {
15
companion object {
16
/** Creates a builder for a regular function */
17
fun builder(name: String): Builder
18
19
/** Creates a builder for a function from a MemberName */
20
fun builder(memberName: MemberName): Builder
21
22
/** Creates a builder for a constructor */
23
fun constructorBuilder(): Builder
24
25
/** Creates a builder for a property getter */
26
fun getterBuilder(): Builder
27
28
/** Creates a builder for a property setter */
29
fun setterBuilder(): Builder
30
}
31
32
/** Builder for constructing FunSpec instances */
33
class Builder {
34
/** Adds modifiers to the function */
35
fun addModifiers(vararg modifiers: KModifier): Builder
36
fun addModifiers(modifiers: Iterable<KModifier>): Builder
37
38
/** Adds type parameters (generics) */
39
fun addTypeVariable(typeVariable: TypeVariableName): Builder
40
fun addTypeVariables(typeVariables: Iterable<TypeVariableName>): Builder
41
42
/** Sets the receiver type for extension functions */
43
fun receiver(receiverType: TypeName): Builder
44
fun receiver(receiverType: KClass<*>): Builder
45
46
/** Sets the return type */
47
fun returns(returnType: TypeName): Builder
48
fun returns(returnType: KClass<*>): Builder
49
50
/** Adds parameters */
51
fun addParameter(parameterSpec: ParameterSpec): Builder
52
fun addParameter(name: String, type: TypeName, vararg modifiers: KModifier): Builder
53
fun addParameter(name: String, type: KClass<*>, vararg modifiers: KModifier): Builder
54
fun addParameters(parameterSpecs: Iterable<ParameterSpec>): Builder
55
56
/** Adds context parameters for context receivers */
57
fun contextReceivers(receiverTypes: Iterable<TypeName>): Builder
58
fun contextReceivers(vararg receiverTypes: TypeName): Builder
59
60
/** Adds code statements to the function body */
61
fun addStatement(format: String, vararg args: Any?): Builder
62
fun addNamedCode(format: String, args: Map<String, *>): Builder
63
fun addCode(codeBlock: CodeBlock): Builder
64
fun addComment(format: String, vararg args: Any?): Builder
65
66
/** Sets the function body as a single expression */
67
fun addCode(format: String, vararg args: Any?): Builder
68
69
/** Adds annotations */
70
fun addAnnotation(annotationSpec: AnnotationSpec): Builder
71
fun addAnnotation(annotation: ClassName): Builder
72
fun addAnnotation(annotation: Class<*>): Builder
73
fun addAnnotation(annotation: KClass<*>): Builder
74
75
/** Adds KDoc documentation */
76
fun addKdoc(format: String, vararg args: Any?): Builder
77
fun addKdoc(block: CodeBlock): Builder
78
79
/** Builds the FunSpec */
80
fun build(): FunSpec
81
}
82
}
83
```
84
85
**Usage Examples:**
86
87
```kotlin
88
import com.squareup.kotlinpoet.*
89
90
// Simple function
91
val greetFunction = FunSpec.builder("greet")
92
.addParameter("name", String::class)
93
.returns(String::class)
94
.addStatement("return %S + name", "Hello, ")
95
.build()
96
97
// Function with multiple parameters and modifiers
98
val calculateFunction = FunSpec.builder("calculate")
99
.addModifiers(KModifier.INLINE)
100
.addParameter("x", Int::class)
101
.addParameter("y", Int::class)
102
.addParameter(
103
ParameterSpec.builder("operation", LambdaTypeName.get(
104
parameters = listOf(
105
ParameterSpec.unnamed(Int::class.asTypeName()),
106
ParameterSpec.unnamed(Int::class.asTypeName())
107
),
108
returnType = Int::class.asTypeName()
109
)).build()
110
)
111
.returns(Int::class)
112
.addStatement("return operation(x, y)")
113
.build()
114
115
// Extension function
116
val stringExtension = FunSpec.builder("isPalindrome")
117
.receiver(String::class)
118
.returns(Boolean::class)
119
.addStatement("return this == this.reversed()")
120
.build()
121
122
// Generic function with constraints
123
val swapFunction = FunSpec.builder("swap")
124
.addTypeVariable(TypeVariableName("T"))
125
.addParameter("list", List::class.asClassName().parameterizedBy(TypeVariableName("T")).copy(nullable = false))
126
.addParameter("i", Int::class)
127
.addParameter("j", Int::class)
128
.returns(UNIT)
129
.addStatement("val temp = list[i]")
130
.addStatement("list[i] = list[j]")
131
.addStatement("list[j] = temp")
132
.build()
133
134
// Suspend function
135
val fetchDataFunction = FunSpec.builder("fetchData")
136
.addModifiers(KModifier.SUSPEND)
137
.addParameter("url", String::class)
138
.returns(String::class)
139
.addStatement("// Implementation would use coroutines")
140
.addStatement("return %S", "mock data")
141
.build()
142
143
// Operator function
144
val plusOperator = FunSpec.builder("plus")
145
.addModifiers(KModifier.OPERATOR)
146
.receiver(ClassName("", "Vector"))
147
.addParameter("other", ClassName("", "Vector"))
148
.returns(ClassName("", "Vector"))
149
.addStatement("return Vector(x + other.x, y + other.y)")
150
.build()
151
```
152
153
### Constructor Specification
154
155
Creates primary and secondary constructors with parameter handling and initialization code.
156
157
```kotlin { .api }
158
// Constructors use FunSpec.constructorBuilder()
159
```
160
161
**Usage Examples:**
162
163
```kotlin
164
// Primary constructor
165
val primaryConstructor = FunSpec.constructorBuilder()
166
.addParameter("name", String::class)
167
.addParameter("age", Int::class)
168
.build()
169
170
// Secondary constructor with delegation
171
val secondaryConstructor = FunSpec.constructorBuilder()
172
.addParameter("name", String::class)
173
.callThisConstructor("name", "0")
174
.build()
175
176
// Constructor with validation
177
val validatingConstructor = FunSpec.constructorBuilder()
178
.addParameter("email", String::class)
179
.addStatement("require(email.contains('@')) { %S }", "Invalid email format")
180
.build()
181
```
182
183
### Property Specification
184
185
Creates property declarations including val/var properties, getters, setters, backing fields, and delegated properties.
186
187
```kotlin { .api }
188
/**
189
* Specification for generating properties
190
*/
191
class PropertySpec private constructor() {
192
companion object {
193
/** Creates a builder for a val property */
194
fun builder(name: String, type: TypeName, vararg modifiers: KModifier): Builder
195
fun builder(name: String, type: KClass<*>, vararg modifiers: KModifier): Builder
196
197
/** Creates a builder for a var property */
198
fun varBuilder(name: String, type: TypeName, vararg modifiers: KModifier): Builder
199
fun varBuilder(name: String, type: KClass<*>, vararg modifiers: KModifier): Builder
200
}
201
202
/** Builder for constructing PropertySpec instances */
203
class Builder {
204
/** Sets whether the property is mutable (var) */
205
fun mutable(mutable: Boolean = true): Builder
206
207
/** Adds modifiers to the property */
208
fun addModifiers(vararg modifiers: KModifier): Builder
209
fun addModifiers(modifiers: Iterable<KModifier>): Builder
210
211
/** Sets the property initializer */
212
fun initializer(format: String, vararg args: Any?): Builder
213
fun initializer(codeBlock: CodeBlock): Builder
214
215
/** Sets a delegated property */
216
fun delegate(format: String, vararg args: Any?): Builder
217
fun delegate(codeBlock: CodeBlock): Builder
218
219
/** Sets a custom getter */
220
fun getter(funSpec: FunSpec): Builder
221
222
/** Sets a custom setter */
223
fun setter(funSpec: FunSpec): Builder
224
225
/** Sets the receiver type for extension properties */
226
fun receiver(receiverType: TypeName): Builder
227
fun receiver(receiverType: KClass<*>): Builder
228
229
/** Adds annotations */
230
fun addAnnotation(annotationSpec: AnnotationSpec): Builder
231
fun addAnnotation(annotation: ClassName): Builder
232
fun addAnnotation(annotation: Class<*>): Builder
233
fun addAnnotation(annotation: KClass<*>): Builder
234
235
/** Adds KDoc documentation */
236
fun addKdoc(format: String, vararg args: Any?): Builder
237
fun addKdoc(block: CodeBlock): Builder
238
239
/** Adds context receivers */
240
fun contextReceivers(receiverTypes: Iterable<TypeName>): Builder
241
fun contextReceivers(vararg receiverTypes: TypeName): Builder
242
243
/** Builds the PropertySpec */
244
fun build(): PropertySpec
245
}
246
}
247
```
248
249
**Usage Examples:**
250
251
```kotlin
252
// Simple val property with initializer
253
val nameProperty = PropertySpec.builder("name", String::class)
254
.initializer("%S", "Unknown")
255
.build()
256
257
// Mutable property with custom getter and setter
258
val temperatureProperty = PropertySpec.builder("temperatureCelsius", Double::class)
259
.mutable(true)
260
.addModifiers(KModifier.PRIVATE)
261
.initializer("0.0")
262
.build()
263
264
val temperatureFahrenheit = PropertySpec.builder("temperatureFahrenheit", Double::class)
265
.getter(
266
FunSpec.getterBuilder()
267
.addStatement("return temperatureCelsius * 9.0 / 5.0 + 32.0")
268
.build()
269
)
270
.setter(
271
FunSpec.setterBuilder()
272
.addParameter("value", Double::class)
273
.addStatement("temperatureCelsius = (value - 32.0) * 5.0 / 9.0")
274
.build()
275
)
276
.build()
277
278
// Const property
279
val maxRetries = PropertySpec.builder("MAX_RETRIES", Int::class)
280
.addModifiers(KModifier.CONST)
281
.initializer("3")
282
.build()
283
284
// Lazy delegated property
285
val expensiveValue = PropertySpec.builder("expensiveValue", String::class)
286
.delegate(CodeBlock.of("lazy { computeExpensiveValue() }"))
287
.build()
288
289
// Extension property
290
val stringLength = PropertySpec.builder("lastChar", Char::class.copy(nullable = true))
291
.receiver(String::class)
292
.getter(
293
FunSpec.getterBuilder()
294
.addStatement("return if (isEmpty()) null else this[length - 1]")
295
.build()
296
)
297
.build()
298
299
// Property with backing field
300
val counter = PropertySpec.varBuilder("counter", Int::class)
301
.addModifiers(KModifier.PRIVATE)
302
.initializer("0")
303
.getter(
304
FunSpec.getterBuilder()
305
.addStatement("return field")
306
.build()
307
)
308
.setter(
309
FunSpec.setterBuilder()
310
.addParameter("value", Int::class)
311
.addStatement("require(value >= 0) { %S }", "Counter cannot be negative")
312
.addStatement("field = value")
313
.build()
314
)
315
.build()
316
```
317
318
### Parameter Specification
319
320
Creates function and constructor parameters with support for default values, vararg, and parameter modifiers.
321
322
```kotlin { .api }
323
/**
324
* Specification for function and constructor parameters
325
*/
326
class ParameterSpec private constructor() {
327
companion object {
328
/** Creates a builder for a named parameter */
329
fun builder(name: String, type: TypeName, vararg modifiers: KModifier): Builder
330
fun builder(name: String, type: KClass<*>, vararg modifiers: KModifier): Builder
331
332
/** Creates an unnamed parameter (for lambda types) */
333
fun unnamed(type: TypeName): ParameterSpec
334
fun unnamed(type: KClass<*>): ParameterSpec
335
}
336
337
/** Builder for constructing ParameterSpec instances */
338
class Builder {
339
/** Adds modifiers to the parameter */
340
fun addModifiers(vararg modifiers: KModifier): Builder
341
fun addModifiers(modifiers: Iterable<KModifier>): Builder
342
343
/** Sets the default value for the parameter */
344
fun defaultValue(format: String, vararg args: Any?): Builder
345
fun defaultValue(codeBlock: CodeBlock): Builder
346
347
/** Adds annotations */
348
fun addAnnotation(annotationSpec: AnnotationSpec): Builder
349
fun addAnnotation(annotation: ClassName): Builder
350
fun addAnnotation(annotation: Class<*>): Builder
351
fun addAnnotation(annotation: KClass<*>): Builder
352
353
/** Adds KDoc documentation */
354
fun addKdoc(format: String, vararg args: Any?): Builder
355
fun addKdoc(block: CodeBlock): Builder
356
357
/** Builds the ParameterSpec */
358
fun build(): ParameterSpec
359
}
360
}
361
```
362
363
**Usage Examples:**
364
365
```kotlin
366
// Simple parameter
367
val nameParam = ParameterSpec.builder("name", String::class).build()
368
369
// Parameter with default value
370
val ageParam = ParameterSpec.builder("age", Int::class)
371
.defaultValue("0")
372
.build()
373
374
// Vararg parameter
375
val itemsParam = ParameterSpec.builder("items", String::class)
376
.addModifiers(KModifier.VARARG)
377
.build()
378
379
// Parameter with annotation
380
val validatedParam = ParameterSpec.builder("email", String::class)
381
.addAnnotation(ClassName("javax.validation.constraints", "Email"))
382
.build()
383
384
// Crossinline lambda parameter
385
val lambdaParam = ParameterSpec.builder("block", LambdaTypeName.get(returnType = UNIT))
386
.addModifiers(KModifier.CROSSINLINE)
387
.build()
388
389
// Reified type parameter
390
val typeParam = ParameterSpec.builder("clazz", Class::class.asClassName().parameterizedBy(TypeVariableName("T")))
391
.build()
392
```
393
394
### Context Parameters and Receivers
395
396
Support for Kotlin's context receivers and extension function receivers.
397
398
```kotlin { .api }
399
// Context receivers are set on FunSpec and PropertySpec builders
400
// Extension receivers are set using receiver() method
401
```
402
403
**Usage Examples:**
404
405
```kotlin
406
// Extension function with receiver
407
val stringExtension = FunSpec.builder("truncate")
408
.receiver(String::class)
409
.addParameter("maxLength", Int::class)
410
.returns(String::class)
411
.addStatement("return if (length <= maxLength) this else substring(0, maxLength) + %S", "...")
412
.build()
413
414
// Function with context receivers (experimental feature)
415
val contextFunction = FunSpec.builder("processWithContext")
416
.contextReceivers(
417
ClassName("", "Logger"),
418
ClassName("", "Database")
419
)
420
.addParameter("data", String::class)
421
.returns(UNIT)
422
.addStatement("log(%S)", "Processing data")
423
.addStatement("save(data)")
424
.build()
425
```