【发布时间】:2016-09-24 04:03:09
【问题描述】:
我有以下代表简单树的类结构。每个项目可以有多个子项和父项。
树根让我头疼。我试图在不使用null 的情况下执行此操作,因此我可以通过调用item.parent 向上遍历树。为了简化它,我希望根以自己为父,但我不知道该怎么做。
interface Item {
val parent: Directory
}
interface ItemWithChildren{
val children: MutableList<Item>
}
class Directory() : Item, ItemWithChildren {
override val children: MutableList<Item> = mutableListOf()
override val parent: Directory by lazy { this }
constructor(par: Directory) : this() {
parent = par //Error: val cannot be reassigned
}
}
class File(override val parent: Directory) : Item
该代码无法编译,因为无法重新分配 val parent。但是使用this 作为默认参数值也是不可能的。有什么办法吗?
如果我允许父级可以为空,那么解决方案很简单。但如果可能的话,我不想使用空值。 null 也会击败 item.parent 链。
【问题讨论】:
标签: kotlin