43

Why has 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
    ...
    ...
    ...
}
Kirby
  • 15,127
  • 10
  • 89
  • 104
LEMUEL ADANE
  • 8,336
  • 16
  • 58
  • 72

4 Answers4

79

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

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
11

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

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

  2. 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.

  3. 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"
    }
}
Kirby
  • 15,127
  • 10
  • 89
  • 104
Rahul
  • 10,457
  • 4
  • 35
  • 55
  • @DanielWilson I am not sure what guidelines you follow. But generally I append temp in front variable name. Or better you can suggest edit. – Rahul Jan 08 '19 at 18:16
0

And another reason is that val and var differ by only one letter. This can be very confusing. So for function parameters they removed the option completely. Thus eliminating the confusion in this one small area (yet keeping it everywhere else--go figure).

SMBiggs
  • 11,034
  • 6
  • 68
  • 83
0

This decision was made to avoid fragile base class problem. It happens when a small change in base classes (superclasses) makes subclasses malfunction.

Nazanin Nasab
  • 595
  • 8
  • 18