can I somehow mutate reassign the receiver in an e...
# getting-started
y
can I somehow mutate reassign the receiver in an extension function? something like
Copy code
fun MyTree?.addChildOrMakeRoot(child: MyTree) = if (this != null) { this.addChild(child) } else { this = child }
🚫 2
e
you cannot change a
this
reference (or any other parameter for that matter)
s
Can you give an example of how you would use the function and what you would want it to do?
y
that is actually a real-life example of how I would use that.
s
C# lets you do this in some cases and it's kinda cursed
y
I have this function that takes a tree root and mutates it, I'd like to replace it with a function that returns either null or the change to the tree
s
Sure, I was interested in how it would look at the call site. I guess you want it to mutate some other variable, outside the function? That's not possible as Kotlin functions always pass by value. But there might be other ways to tackle the problem.
y
basically it does some BFS and mutates the tree node, I'd like it to capture an outside nullable tree node and mutate that, then return it
e
Copy code
class MyTreeHolder(var root: MyTree?)
fun MyTreeHolder.addChildOrMakeRoot(child: MyTree) = root?.addChild(child) ?: run { root = child }
👍 1
thank you color 1
y
yeah that would work, thanks