final or val function parameter or in Kotlin?

2019-02-16 06:28发布

问题:

Why does Kotlin removed the final or val function parameter which is very useful in Java?

fun say(val msg: String = "Hello World") {
    msg = "Hello To Me" // would give an error here since msg is val    
                        //or final
    ...
    ...
    ...
}

回答1:

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



回答2:

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"
    }
}


标签: kotlin