xref: /aosp_15_r20/external/kotlinpoet/docs/interfaces.md (revision 3c321d951dd070fb96f8ba59e952ffc3131379a0)
1Interfaces
2==========
3
4KotlinPoet has no trouble with interfaces. Note that interface methods must always be `ABSTRACT`.
5The modifier is necessary when defining the interface:
6
7```kotlin
8val helloWorld = TypeSpec.interfaceBuilder("HelloWorld")
9  .addProperty("buzz", String::class)
10  .addFunction(
11    FunSpec.builder("beep")
12      .addModifiers(KModifier.ABSTRACT)
13      .build()
14  )
15  .build()
16```
17
18But these modifiers are omitted when the code is generated. These are the default so we don't need
19to include them for `kotlinc`'s benefit!
20
21```kotlin
22interface HelloWorld {
23  val buzz: String
24
25  fun beep()
26}
27```
28
29Kotlin 1.4 adds support for functional interfaces via `fun interface` syntax. To create this in
30KotlinPoet, use `TypeSpec.funInterfaceBuilder()`.
31
32```kotlin
33val helloWorld = TypeSpec.funInterfaceBuilder("HelloWorld")
34  .addFunction(
35    FunSpec.builder("beep")
36      .addModifiers(KModifier.ABSTRACT)
37      .build()
38  )
39  .build()
40
41// Generates...
42fun interface HelloWorld {
43  fun beep()
44}
45```
46