I have following class structure which represents simple tree. Each item can have multiple children and parent.
The tree root is causing me a headache though. I'm trying to do this without using null
so I can traverse the tree upwards by calling item.parent
. To simplify it I want the root to has itself as a parent, but I cannot figure out how to do it.
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
That code doesn't compile, because it's not possible to reassign the val parent
. But using this
as a default parameter value is also not possible. Is there any way out?
If I allow the parent to be nullable, then the solution is easy. But I don't wanna use the nulls, if possible. Also null
would defeat the item.parent
chain.