+ 1
[SOLVED] How to make funktion argument immutable
Here I'm using recursively calls of some functions to walk a tree. But I can't do that like this: inOrderWalk(node.leftChild) Kotlin says: Argument has to be immutable. Now I'm "wrapping" each reference to the child in a list and use the list as argument. nextNode = listOf<Node>(node.leftChild) inOrderWalk(nextNode) This works because Lists are immutable. My question: Are there other/better options to do this? https://code.sololearn.com/cWfj6T0ezhbP/?ref=app
5 Antworten
+ 2
The issue isn't because of argument mutability but rather because Node.left/right is nullable. This works:
fun inOrderWalk(node:Node):Unit {
if (node.left != null) {
inOrderWalk(node.left!!)
}
println(node.element)
if (node.right != null) {
inOrderWalk(node.right!!)
}
}
or even:
fun inOrderWalk(node:Node):Unit {
node.left?.let {
inOrderWalk(it)
}
println(node.element)
node.right?.let {
inOrderWalk(it)
}
}
+ 2
What the ... 😮
That's unbelievable.
The given error message is not really a great help 🤔😞😩
bornToCode() I thank you so much👍
+ 2
Yeah, sometimes the error messages can be a bit cryptic lol. Glad to help.
+ 1
Arguments to Kotlin functions are immutable in that you cannot reassign them. So the following code will not compile:
fun doSomething(data: String) {
data = "new data"
}
If you remove the lists from your code and just use the node objects directly it will run just fine.
0
bornToCode() yes, your example is clear for me.
But w/o this "wrapping" I got errors regarding the mutable note attributes.
Here a short try w/o this list.
Idk, I'm doing something wrong.
https://code.sololearn.com/c0XavQPzO3Qv/?ref=app