final or val function parameter or in Kotlin?

Kotlin function parameters are final. There is no val or final keyword because that's the default (and can't be changed).


After Kotlin M5.1 support of mutable parameters removed, In earlier versions that can be achieve using

fun foo(var x: Int) {
  x = 5
}

According to Kotlin developers, main reasons of removing this feature are below -

  1. 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).

  2. Another source of confusion is primary constructors: “val” or “var” in a constructor declaration means something different from the same thing if a function declarations (namely, it creates a property).

  3. Also, we all know that mutating parameters is no good style, so writing “val” or “var” infront of a parameter in a function, catch block of 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"
    }
}

Tags:

Kotlin