Let's say I have two interfaces in a project:
interface InterfaceA {
// ...
interface Listener {
// ...
}
}
interface InterfaceB {
// ...
interface Listener {
// ...
}
}
and I declare both of them and their listeners for annotation processing using Kotlin Poet's ClassName, eg.
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"),
)
The class I have to generate uses all of the aforementioned types: InterfaceA, InterfaceA.Listener, InterfaceB, InterfaceB.Listener. That results in generating the following imports, producing compilation error due to ambigouos Listener imports.
import com.example.a.InterfaceA
import com.example.a.InterfaceA.Listener
import com.example.b.InterfaceB
import com.example.b.InterfaceB.Listener
Is there any way to get rid of the listener imports, since they're not really necessary? Or is there any other way to approach the issue?
Thanks for any help!
The
Listeners aren't actually in a package calledcom.example.a.InterfaceAorcom.example.a.InterfaceB. They are nested types inInterfaceAandInterfaceB.You can create
ClassNames representing nested types using thenestedClassmethod.Example:
This outputs:
Notice that only
InterfaceAandInterfaceBare imported.Even if the
Listeners are not nested types, and are actually top-level interfaces in different packages. KotlinPoet can still resolve the conflict by using aliased imports.That is, if you actually did:
KotlinPoet would generate: