【问题标题】:How to cross-reference types in parameters [duplicate]如何在参数中交叉引用类型
【发布时间】:2017-07-07 09:54:52
【问题描述】:

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

【问题讨论】:

标签: java android-studio kotlin


【解决方案1】:

我不喜欢这样。因为它会引入另一个泛型参数。而是可以引入一个中间角色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>

注意out 变量是可选的。

【讨论】:

  • 很好的解决方案!如果你在重复的问题上写下这个答案,我可以在那里投票并删除这个问题。
  • @Simas 先生,感谢您接受我的回答。但我英语不好,我不喜欢重复。让它住在这里。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 2020-03-03
  • 1970-01-01
  • 2021-04-07
相关资源
最近更新 更多