How do I generate a class which extends a class which implements a generic interface using kotlinpoet

1.2k Views Asked by At

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
1

There are 1 best solutions below

3
On BEST ANSWER

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()
    }
}