Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to re assign local variables

Tags:

kotlin

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

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

Are local variables read only in Kotlin?

like image 301
user3282666 Avatar asked Jan 06 '23 01:01

user3282666


1 Answers

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
}
like image 97
nhaarman Avatar answered Jan 19 '23 12:01

nhaarman