Hi all. I am using data class for my database enti...
# getting-started
g
Hi all. I am using data class for my database entities. I have a parent child relationship, where child has a reference to a parent and a parent has a collection of its children. So a parent references a child and the child references the parent. A circular reference. How to create parent and child, taking into account that they are immutable?
@Ruckus rethink, but how? My database entity has a reference to a parent (foreign key).
Btw. Thanks a lot for the code snippet btw. I think I got it. So Parent has a list of children. I create a parent with an empty list and then add children there. Thank you so much.
Well, if I look at my database structure. The parent column is nullable. Btw parent and child is the same entity represented by the same type in the application code.
Could you advise anything to read on the topic? Books, etc?
Thanks a lot. Very interesting read.
g
You could start with one of the links empty and then create a changed version (
.copy()
) that contains the second link.
g
@Goetz Markgraf Immutable properties do not work for circular references:
Copy code
parent = 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.
g
Sorry, you‘re absolutely right
g
hi all. I finally went back to implement this in my code. I got this result:
Copy code
data 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.