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
4

1 回答 1

6

您可以将 aParameterizedTypeName作为参数传递给addSuperinterface. 要创建ParameterizedTypeName您可以使用KClass<*>.parameterizedBy扩展功能

例子

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)

输出

package com.example    

class BooBuilder : Builder<Boo> {
    override fun build(): Boo {
        TODO()
    }
}
于 2018-12-15T07:00:40.070 回答