Fred Friis
06/06/2024, 11:38 PMdata class Order(
val orderId: String,
...
val check: Check
)
data class Check(
val checkId: String,
...
)
we'd like them to be able to reference each other 🧵Fred Friis
06/06/2024, 11:39 PMdata class Order(
val orderId: String,
...
val check: Check
)
data class Check(
val order: Order, //parent
val checkId: String,
...
)
but then we have a circular reference, and we can't instantiate them
val myOrder = MyOrder(
orderId = "1",
foo = "foo",
check = MyCheck(
checkId = "2",
bar = "bar",
order = myOrder //doesn't compile
)
)
we can mark the reference attributes as lateinit var, but then they object are mutable and we don't want that 😕 is there a way to solve this? I guess we could cheat and like use Jackson to instantiate them from json string representations, but... that's not idealephemient
06/06/2024, 11:49 PMclass Order {
val orderId: String
val check: Check
constructor(orderId: String, check: Check) {
this.orderId = orderId
this.check = check
}
constructor(orderId: String, checkId: String) {
this.orderId = orderId
check = Check(checkId = checkId, order = this)
}
override fun toString(): String = "Order(orderId=$orderId, checkId=${check.checkId})"
}
class Check {
val checkId: String
val order: Order
constructor(checkId: String, order: Order) {
this.checkId = checkId
this.order = order
}
constructor(checkId: String, orderId: String) {
this.checkId = checkId
order = Order(orderId = orderId, check = this)
}
override fun toString(): String = "Check(checkId=$checkId, orderId=${order.orderId})"
}
but I don't really recommend it. you can't have structural equality or hashcode with self-recursive dataFred Friis
06/06/2024, 11:50 PMFred Friis
06/06/2024, 11:51 PMephemient
06/06/2024, 11:51 PMtoString()
to avoid that, in the example aboveephemient
06/06/2024, 11:52 PMdata class OrderAndCheck(val order: Order, val check: Check)
to hold them together, without having any direct references from one to the otherFred Friis
06/06/2024, 11:54 PMFred Friis
06/07/2024, 12:18 AMCLOVIS
06/10/2024, 4:00 PMephemient
06/10/2024, 4:10 PMOn the JVM, you can't have two immutable objects that reference each other.I gave an example which does exactly that https://kotlinlang.slack.com/archives/C0B8RC352/p1717717766193559?thread_ts=1717717130.233709&cid=C0B8RC352 because objects are not immutable until initialization is completed. leaking
this
before the constructor is complete is not recommended but is easily doableephemient
06/10/2024, 4:12 PMFred Friis
06/10/2024, 4:13 PM