假设我在一个项目中有两个接口:

interface InterfaceA {
    // ...
    interface Listener {
        // ...
    }
}

interface InterfaceB {
    // ...
    interface Listener {
        // ...
    }
}

并且我使用Kotlin Poet的ClassName声明它们和它们的侦听器进行注释处理,例如.

fun InterfaceA() = ClassName(
    packageName = "com.example.a",
    simpleNames = arrayOf("InterfaceA"),
)

fun InterfaceAListener() = ClassName(
    packageName = "com.example.a.InterfaceA",
    simpleNames = arrayOf("Listener"),
)

fun InterfaceB() = ClassName(
    packageName = "com.example.b",
    simpleNames = arrayOf("InterfaceB"),
)

fun InterfaceBListener() = ClassName(
    packageName = "com.example.b.InterfaceB",
    simpleNames = arrayOf("Listener"),
)

我必须生成的类使用前面提到的所有类型:InterfaceAInterfaceA.ListenerInterfaceBInterfaceB.Listener.这会导致生成以下导入,并由于歧义Listener导入而产生编译错误.

import com.example.a.InterfaceA
import com.example.a.InterfaceA.Listener
import com.example.b.InterfaceB
import com.example.b.InterfaceB.Listener

有没有办法go 掉监听器导入,因为它们实际上并不是必需的?或者,有没有其他方法来解决这个问题?

谢谢你的帮助!

推荐答案

Listener实际上并不在名为com.example.a.InterfaceAcom.example.a.InterfaceB的套餐中.它们是InterfaceAInterfaceBnested种类型.

您可以使用nestedClass方法创建表示嵌套类型的ClassName.

示例:

val listenerA = ClassName("com.example", "InterfaceA").nestedClass("Listener")
val listenerB = ClassName("com.example", "InterfaceB").nestedClass("Listener")
FileSpec.builder("", "Foo")
    .addProperty(
        PropertySpec.builder("foo", listenerA).build()
    )
    .addProperty(
        PropertySpec.builder("bar", listenerB).build()
    )
    .build()
    .writeTo(System.out)

这会产生以下结果:

import com.example.InterfaceA
import com.example.InterfaceB

public val foo: InterfaceA.Listener

public val bar: InterfaceB.Listener

请注意,仅导入了InterfaceAInterfaceB.


即使Listener不是嵌套类型,实际上是不同包中的顶级接口.KotlinPoet仍然可以通过使用别名导入来解决冲突.

也就是说,如果你真的这么做了:

val listenerA = ClassName("com.example.InterfaceA", "Listener")
val listenerB = ClassName("com.example.InterfaceB", "Listener")

KotlinPoet将生成:

import com.example.InterfaceA.Listener as InterfaceAListener
import com.example.InterfaceB.Listener as InterfaceBListener

Kotlin相关问答推荐

带有Spring Boot和Kotline的可嵌入实体

如何为集成测试配置Gradle JVM测试套件?

Kotlin异步不并行运行任务

Kotlin:有限的并行性并不是限制并行性

两个LocalDateTime之间的Kotlin差异

CompositionLocal 究竟如何以及何时隐式设置值?

collectAsState 未从存储库接收更改

kotlin短路列表判断吗?

Kotlin .如何用从 1 到 90 的 5 个唯一数字填充列表中的每一行?

使用纯 Kotlin 函数作为 Junit5 方法源

Kotlin 中列表或数组的乘积

在 kotlin 中写入 parcer 可空值

如何将超过 2 个 api 调用的结果与 Coroutines Flow 结合起来?

如何在 kotlin 中生成 json 对象?

将多个 Kotlin 流合并到一个列表中,而无需等待第一个值

Android EditText 协程go 抖操作符,如 RxJava

在Kotlin中为Android编写库会有开销吗?

Kotlin out-projected 类型禁止使用

Kotlin中保留的关键字是什么?

Android room DAO 接口不适用于继承