After Kotlin M5.1 support of mutable parameters has been removed. In earlier versions that can be achieved using
fun foo(var x: Int) {
x = 5
}
According to Kotlin developers, the main reasons for removing this feature are
It 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, mutating parameters is not good style, so writing val
or var
in front of a parameter in a function, catch block or for-loop is no longer allowed.
Summary - All parameter values are val
now. You have to introduce separate variable for re-initialising. Example:
fun say(val msg: String) {
var tempMsg = msg
if(yourConditionSatisfy) {
tempMsg = "Hello To Me"
}
}