LEMUEL  ADANE
LEMUEL ADANE

Reputation: 8818

final or val function parameter or in Kotlin?

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

Upvotes: 45

Views: 31596

Answers (4)

Rahul
Rahul

Reputation: 10635

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

Upvotes: 11

Nazanin Nasab
Nazanin Nasab

Reputation: 625

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

Upvotes: 0

SMBiggs
SMBiggs

Reputation: 11688

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

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691805

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

Upvotes: 84

Related Questions