如何在KotlinPoet中实现Comparable?

时间:2018-05-11 15:57:34

标签: kotlin kotlinpoet

Fleshgrinder GitHub提交。

如何为当前正在生成的类实现Comparable

ParameterizedTypeName.get(Comparable::class, ?)方法,但不清楚如何传递第二个参数。生成类时唯一可用的是ClassName

最小例子:

FileSpec.builder("com.fleshgrinder", "KotlinPoet").apply {
    val className = ClassName("com.fleshgrinder", "KotlinPoet")
    addType(TypeSpec.classBuilder(className).apply {
        addSuperinterface(ParameterizedTypeName.get(Comparable::class, Any::class))
    }.build())
}.build().writeTo(System.out)

生成:

package com.fleshgrinder

import kotlin.Any
import kotlin.Comparable

class KotlinPoet : Comparable<Any>

我想拥有什么:

package com.fleshgrinder

class KotlinPoet : Comparable<KotlinPoet>

1 个答案:

答案 0 :(得分:1)

ParameterizedTypeName具有以下工厂方法:

fun get(rawType: ClassName, vararg typeArguments: TypeName)

以下是如何将其应用于您的用例:

val className = ClassName("com.fleshgrinder", "KotlinPoet")
val comparable = ParameterizedTypeName.get(Comparable::class.asClassName(), className)