xref: /aosp_15_r20/external/kotlinpoet/docs/constructors.md (revision 3c321d951dd070fb96f8ba59e952ffc3131379a0)
1Constructors
2============
3
4`FunSpec` is a slight misnomer; it can also be used for constructors:
5
6```kotlin
7val flux = FunSpec.constructorBuilder()
8  .addParameter("greeting", String::class)
9  .addStatement("this.%N = %N", "greeting", "greeting")
10  .build()
11
12val helloWorld = TypeSpec.classBuilder("HelloWorld")
13  .addProperty("greeting", String::class, KModifier.PRIVATE)
14  .addFunction(flux)
15  .build()
16```
17
18Which generates this:
19
20```kotlin
21class HelloWorld {
22  private val greeting: String
23
24  constructor(greeting: String) {
25    this.greeting = greeting
26  }
27}
28```
29
30For the most part, constructors work just like methods. When emitting code, KotlinPoet will place
31constructors before methods in the output file.
32
33Often times you'll need to generate the primary constructor for a class:
34
35```kotlin
36val helloWorld = TypeSpec.classBuilder("HelloWorld")
37  .primaryConstructor(flux)
38  .addProperty("greeting", String::class, KModifier.PRIVATE)
39  .build()
40```
41
42This code, however, generates the following:
43
44```kotlin
45class HelloWorld(greeting: String) {
46  private val greeting: String
47
48  init {
49    this.greeting = greeting
50  }
51}
52```
53
54By default, KotlinPoet won't merge primary constructor parameters and properties, even if they share
55the same name. To achieve the effect, you have to tell KotlinPoet that the property is initialized
56via the constructor parameter:
57
58```kotlin
59val flux = FunSpec.constructorBuilder()
60  .addParameter("greeting", String::class)
61  .build()
62
63val helloWorld = TypeSpec.classBuilder("HelloWorld")
64  .primaryConstructor(flux)
65  .addProperty(
66    PropertySpec.builder("greeting", String::class)
67      .initializer("greeting")
68      .addModifiers(KModifier.PRIVATE)
69      .build()
70  )
71  .build()
72```
73
74Now we're getting the following output:
75
76```kotlin
77class HelloWorld(private val greeting: String)
78```
79
80Notice that KotlinPoet omits `{}` for classes with empty bodies.
81