【问题标题】:How to implement Comparable in KotlinPoet?如何在 KotlinPoet 中实现 Comparable?
【发布时间】:2018-05-11 15:57:34
【问题描述】:

FleshgrinderGitHub 上提交。

如何为当前正在生成的类实现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>

【问题讨论】:

    标签: kotlin kotlinpoet


    【解决方案1】:

    ClassName有如下扩展方法:

    fun ClassName.parameterizedBy(vararg typeArguments: TypeName)
    

    您可以将它应用到您的用例中:

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

    请注意,由于IDE bug,您需要手动添加以下导入:

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

    【讨论】:

    • 谢谢@АлександрКундрюков,我已经更新了答案!
    猜你喜欢
    • 2014-05-13
    • 2014-06-25
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多