Gasan
12/20/2023, 9:25 PMRuckus
12/20/2023, 9:31 PMdata class Parent(val children: List<Child>)
data class Child(val parent: Parent)
val children = mutableListOf<Child>()
val parent = Parent(children)
repeat(10) {
children += Child(parent)
}
but it's a bit hacky. You may want to rethink your data structure.Gasan
12/20/2023, 9:34 PMRuckus
12/20/2023, 9:36 PMGasan
12/20/2023, 9:38 PMRuckus
12/20/2023, 9:38 PMdata class Parent {
val children = mutableListOf<Children>()
}
data class Child(val parent: Parent)
or
data class Parent(val children: List<Child>)
data class Child {
lateinit var parent: Parent
}
Gasan
12/20/2023, 9:40 PMGasan
12/20/2023, 9:43 PMRuckus
12/20/2023, 9:48 PMval children = mutableMapOf<Thing: MutableList<Thing>>()
, as I find the children collection is often used in one particular place in the app and so maintaining it for the entire app is a waste (and tends to bite me later), but again, that entirely depends on your use case.
> Could you advise anything to read on the topic? Books, etc?
I can't think of anything off the top of my head. This is based on my own experience, so take it with the usual grain of salt.
In my experience, the parent reference is often useful from a functionality standpoint, whereas the tree decedent structure if often just for display purposes, in which case a separate map is great, or more likely just the generic class provided by your graphics library for displaying tree content.Ruckus
12/20/2023, 9:52 PMGasan
12/20/2023, 11:18 PMGoetz Markgraf
12/21/2023, 7:33 AM.copy()
) that contains the second link.Gasan
12/21/2023, 9:17 AMparent = Parent()
child = Child(parent)
parent.copy(child = child)
The child of the parent has a link to the old parent without children, not the new one.
For circular references some form of mutability is required. See options in previous replies.Goetz Markgraf
12/21/2023, 9:45 AMGasan
03/18/2024, 5:20 PMdata class Entity(val name, val parent: Entity?, var children: List<Entity>?)
1. parent
and children
is a part of the data class because I want to copy()
them
2. I must override equals()
, hashCode()
and toString()
otherwise I get stack overflow error.