Why is var or val not allowed in a functions' parameter in kotlin?

Viewed 1753

fun myfunction(a:String) //this is valid

fun myfunction(var a:String) //this is invalid

fun myfunction(val a:String) //this is invalid

1 Answers

The support for var was removed way back from kotlin with the following reason:

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 if a function declarations (namely, it creates a property). 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.

More details in https://blog.jetbrains.com/kotlin/2013/02/kotlin-m5-1/.

Related