Mutable function parameters

How can a function has mutable parameters?

It can’t. What are you trying to achieve?

1 Like

This isn’t possible: in Kotlin, function/method parameters can’t be changed to point to different objects. (Though those objects can themselves be mutable, i.e. have their properties changed.)

In fact, early versions of Kotlin allowed parameters to be changed (like Java, C, and many other languages), but this was altered about 10 years ago. It was announced on the JetBrains blog, where they said:

The main reason is that this was confusing: people tend to think that this means passing a parameter by reference, which we do not support (it is costly at runtime). Another source of confusion is primary constructors: “val” or “var” in a constructor declaration means something different from the same thing in a function declaration (namely, it creates a property). Also, we all know that mutating parameters is not good style

(I’ve made a few trivial edits for grammar.)

See also this previous question, where JetBrains reiterated that policy (and most people agreed).

My own experience agrees with that: the rare cases where it would make sense to mutable parameters (e.g. to convert them to some canonical form or replace nulls) are easily handled by creating a local variable, but the subtle bugs and confusion that can result from making them mutable is much harder to work around.

See also these questions on StackOverflow.

2 Likes

Note that you can shadow function argument, which sort of mimic mutable function parameters:

fun foo(bar: Int) {
    var bar = bar + 1
    bar += 1
    println(bar)
}

fun main() {
    foo(1) // prints 3
}

Well, I would not recommend it, but it is possible.

The solution is very simple as you consider to pass reference types to functions.

1- create a generic wrapper like this

data class <T> Wrapper(var value: T)

2- embed values within it like this

val myInt = Wrapper(123)
val myStr = Wrapper("Hello World!")

3- define your param(s) function(s) taking specialised Wrapper type or not like this, and mutating Wrapped values

fun mutatingParamFunc(aInt: Wrapper<Int>, aStr: Wrapper<String>, aStuff: Wrapper<*>) {
     aInt.value = 321
     aStr.value = "Hello Earth!"
}

mutatingParamFunc(myInt, myStr, myStuff)
println(myInt.value)
println(myStr.value)

// >> 321
// >> Hello Earth!
1 Like