1

I've following Kotlin method

fun getpower(base:Int,power:Int):Int
{
    var result = 1
    while(power > 0){
        result = result * base
        power-- // <---- error in this line
    }
    return result
}

Kotlin compiler gives following error Error:(6, 8) Val cannot be reassigned

What's wrong with updating the variable?

Al Mamun
  • 944
  • 9
  • 27

4 Answers4

3

What's wrong with updating the variable?

The others answer the question by effectively saying "because Kotlin function parameters are immutable." Of course, that is a(the) correct answer.

But given the fact so many languages, including Java, allow you to re-assign function parameters, it might be valid to interpret your question as "why does Kotlin disallow re-assigning function parameters?"

My Answer: Kotlin and Swift have many features in common, so I went to Swift 3 to see why they decided to deprecate function parameter re-assignment and found this motivation.

Using var annotations on function parameters have limited utility, optimizing for a line of code at the cost of confusion with inout , which has the semantics most people expect. To emphasize the fact these values are unique copies and don't have the write-back semantics of inout , we should not allow var here.

In summary, the problems that motivate this change are:

• var is often confused with inout in function parameters.

• var is often confused to make value types have reference semantics.

•Function parameters are not refutable patterns like in if-, while-, guard-, for-in-, and case statements.

Of course, Kotlin has no inout decoration. But the writers could have chosen to allow val and var, with val being the default. Then they would have had behavior consistent with many other languages. Instead, they opted for code clarity.

The OPs example code shows a valid example of when parameter re-assignment is clear and natural. Having to add one more line to a very short function (to get a local variable to do what the parameter variable could have done) IMHO reduces clarity. Again, IMHO, I would have preferred optionally being able to declare my parameters as var.

Community
  • 1
  • 1
Les
  • 10,335
  • 4
  • 40
  • 60
2

A function's parameters inside the function are read-only (like variables created with val), therefore they cannot be reassigned.

You can see discussions about this design decision here and here.

zsmb13
  • 85,752
  • 11
  • 221
  • 226
0

In Kotlin, method parameter's are val(non-mutable) type not var(mutable) type. Similar as java final. That's why i cant mutate(change) that .

Al Mamun
  • 944
  • 9
  • 27
0

The error you saw has more to do with scoping. A function's parameter by design is immutable or more accurately, read-only and that is what the val keyword stands for that is why you see that error.

Alf Moh
  • 7,159
  • 5
  • 41
  • 50