LastExceed
01/01/2020, 11:28 AMdata class Node(
val author: String,
val message: String,
val children: List<Node>,
val parent: Node = this
)
why is this not defined in this context ?
context: Im making a chat client with tree structure instead of linear conversation. Every message is a comment on the message it replies to, except the root node which is a comment on itself (or should i make it nullable? i like to avoid nullability whenever possible)Kashif
01/01/2020, 11:33 AMthis is not yet createdLastExceed
01/01/2020, 11:33 AMKashif
01/01/2020, 11:34 AMKashif
01/01/2020, 11:37 AMKashif
01/01/2020, 11:37 AMdata class Node(
val author: String,
val message: String,
val children: List<Node>,
val parent: Node?
)LastExceed
01/01/2020, 11:38 AMKashif
01/01/2020, 11:39 AMdata class Node(
val author: String,
val message: String,
val children: List<Node>,
var parent: Node
) {
init {
parent = this
}
}Kashif
01/01/2020, 11:39 AMLastExceed
01/01/2020, 11:41 AMLastExceed
01/01/2020, 11:41 AMLastExceed
01/01/2020, 11:41 AMKashif
01/01/2020, 11:41 AMLastExceed
01/01/2020, 11:42 AMKashif
01/01/2020, 11:42 AMMarc Knaup
01/01/2020, 11:44 AM.toString(), .equals() or .hashCode() on them will cause a StackOverflowError.LastExceed
01/01/2020, 11:44 AMLastExceed
01/01/2020, 11:44 AMMarc Knaup
01/01/2020, 11:45 AMLastExceed
01/01/2020, 11:45 AMMarc Knaup
01/01/2020, 11:46 AMLastExceed
01/01/2020, 11:46 AMMarc Knaup
01/01/2020, 11:46 AMdata class afaik.Marc Knaup
01/01/2020, 11:46 AMKashif
01/01/2020, 11:47 AMLastExceed
01/01/2020, 11:47 AMLastExceed
01/01/2020, 11:48 AMdata keyword i still get the same errorMarc Knaup
01/01/2020, 11:48 AMclass Node {
val parent = this
}Marc Knaup
01/01/2020, 11:49 AMval, so they cannot use this since you’re in the constructor.Marc Knaup
01/01/2020, 11:49 AMMarc Knaup
01/01/2020, 11:50 AMthis is already known when the default value is evaluated.Marc Knaup
01/01/2020, 11:50 AMLastExceed
01/01/2020, 11:50 AMMarc Knaup
01/01/2020, 11:51 AMLastExceed
01/01/2020, 11:51 AMKashif
01/01/2020, 11:52 AMMarc Knaup
01/01/2020, 11:53 AMclass Node private constructor(parent: Node?, foo: Unit) {
val parent = parent ?: this
constructor(parent: Node = useThis) :
this(parent = parent.takeIf { it !== useThis }, foo = Unit)
companion object {
private val useThis = Node(parent = null, foo = Unit)
}
}LastExceed
01/01/2020, 11:58 AMclass Node(
val author: String,
val message: String,
val children: List<Node>,
parent: Node? = null
) {
val parent = parent ?: this
}
wouldn't this suffice ?Marc Knaup
01/01/2020, 12:00 PMLastExceed
01/01/2020, 12:04 PMparent is non-nullable which is was i was aiming for. to be fair, the parameter specifying the value of a non-nullable variable being nullable is a mess, but frankly so is your solution 😄LastExceed
01/01/2020, 12:05 PM