3

Given an interface like

interface Builder<R> {
    fun build() : R
}

How do I generate a class BooBuilder which implements this interface using kotlinpoet.

I couldn't find an example on creating a generic interface (or class) in the documentation.

what I would like would start with

class BooBuilder(): Builder<Boo> { //...

I understand that I should start with

TypeSpec
  .classBuilder("BooBuilder")
  .addSuperinterface( /* I have no idea what to put here */ )
  // add methods
Lukasz
  • 2,257
  • 3
  • 26
  • 44

1 Answers1

6

You can pass a ParameterizedTypeName as a parameter to addSuperinterface. To create the ParameterizedTypeName you can use KClass<*>.parameterizedBy extention function

Example

import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy


val booKClass = Boo::class

val booBuilderType = TypeSpec
    .classBuilder("BooBuilder")
    .addSuperinterface(Builder::class.parameterizedBy(booKClass))
    .addFunction(
        FunSpec.builder("build")
            .addModifiers(KModifier.OVERRIDE)
            .addStatement("TODO()")
            .returns(booKClass)
            .build()
    )
    .build()

val kotlinFile = FileSpec.builder("com.example", "BooBuilder")
    .addType(booBuilderType)
    .build()

kotlinFile.writeTo(System.out)

Output

package com.example    

class BooBuilder : Builder<Boo> {
    override fun build(): Boo {
        TODO()
    }
}
Omar Mainegra
  • 4,006
  • 22
  • 30
  • 2
    Thank's a lot. A piece of additional information, for anyone reading this in the future. You need to `import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy` – Lukasz Dec 16 '18 at 14:25
  • Yeah, @Lukasz, it was troublesome to me too, I'll update the answers – Omar Mainegra Dec 16 '18 at 15:06
  • 1
    Right, there's a longstanding IDE issue where it won't import extension functions defined in companion objects, it should be fixed in 1.3.20. For now, just add the import manually. – Egor Dec 16 '18 at 16:43