[SOLVED] How to make funktion argument immutable | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

3rd Oct 2021, 9:40 AM
Coding Cat
Coding Cat - avatar
5 Answers
+ 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) } }
25th Oct 2021, 2:26 PM
bornToCode()
bornToCode() - avatar
+ 2
What the ... 😮 That's unbelievable. The given error message is not really a great help 🤔😞😩 bornToCode() I thank you so much👍
25th Oct 2021, 2:43 PM
Coding Cat
Coding Cat - avatar
+ 2
Yeah, sometimes the error messages can be a bit cryptic lol. Glad to help.
25th Oct 2021, 2:44 PM
bornToCode()
bornToCode() - avatar
+ 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.
25th Oct 2021, 10:38 AM
bornToCode()
bornToCode() - avatar
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
25th Oct 2021, 11:14 AM
Coding Cat
Coding Cat - avatar