我正在尝试在通用参数中交叉引用类型。 在java中,我有这个:
public interface Group<C extends Child> {
List<C> getChildren();
}
public interface Child<G extends Group> {
G getParent();
}
class MyGroup implements Group<MyChild> {
@Override
public List<MyChild> getChildren() {
return null;
}
}
class MyChild implements Child<MyGroup> {
@Override
public MyGroup getParent() {
return null;
}
}
使用 AndroidStudio 的“转换为 Kotlin”功能会导致:
interface Group<C : Child<*>> {
val children: List<C>
}
interface Child<G : Group<*>> {
val parent: G
}
internal inner class MyGroup : Group<MyChild> {
override val children: List<MyChild>?
get() = null
}
internal inner class MyChild : Child<MyGroup> {
override val parent: MyGroup?
get() = null
}
抛出:违反有限界限制。
有什么办法可以在 kotlin 中编写这样的代码吗?
最佳答案
我不喜欢这样。因为它会引入另一个通用参数。相反,你可以引入一个中间角色Node
接口(interface)来描述关系,例如:
interface Node<out T>;
interface Group<out C : Node<*>> : Node<C> {
val children: List<C>
}
interface Child<out G : Group<*>> : Node<G> {
val parent: G;
}
class MyGroup : Group<MyChild> {
override val children: List<MyChild>
get() = TODO("not implemented")
}
class MyChild : Child<MyGroup> {
override val parent: MyGroup
get() = TODO("not implemented")
}
中间角色就像kotlin.Function
:
public interface Function<out R>
注意:out
方差是可选的。
关于java - 如何交叉引用参数中的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44967861/