如何在参数中交叉引用类型

时间:2017-07-07 09:54:52

标签: java android-studio kotlin

我正在尝试在其通用参数中交叉引用类型。 在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中编写这样的代码吗?

1 个答案:

答案 0 :(得分:2)

我不喜欢这样。因为它会引入另一个通用参数。相反,您可以引入中间角色<android.support.v7.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimay >界面来描述关系,例如:

Node

中间角色就像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> 方差是可选的。