user3282666
user3282666

Reputation: 670

Unable to re assign local variables

fun test(temp: Int) {
    temp = 5
}

The compiler throws an error saying "val cannot be reassigned".

Are local variables read only in Kotlin?

Upvotes: 4

Views: 525

Answers (2)

Adam Dziedzic
Adam Dziedzic

Reputation: 41

temp is not a local variable - it is a function parameter. There is no point of reassigning it.

Upvotes: 0

nhaarman
nhaarman

Reputation: 100378

Function parameters are always read-only (i.e. declared as val);
If you want to change it, you will need to use a (new) local variable:

fun test(temp: Int) {
   var myTemp = temp
   myTemp = 5
}

Upvotes: 9

Related Questions