parameterskotlin

Val cannot be reassigned a compile time error for a local variable in fun in Kotlin


Here in fun swap I am trying to change the value of a1 with b1, but it shows "val cannot be reassigned compile time error". If I can't change like this, then how is it possible to do?

fun swap(a1: String, b1: String) {
   val temp = a1
   a1 = b1
   b1 = temp
}

Note: This is just a sample to know why I am not able to reassign the local variable as we can do in Java.


Solution

  • In Kotlin val declares final, read only, reference - and that is exactly what compiler error is telling you with

    Val cannot be reassigned

    Once you assign value to val, it cannot be changed. If you want to be able to reassign it you have to declare it as var

    In Kotlin method parameters are implicitly declared as final val, so you cannot reassign them just like you could in Java.

    But the core error in your code is that you are trying to swap method parameters. Since method parameters are passed by value and not by reference what you want to achieve is impossible in Kotlin (just as well as it is impossible in Java). Even if you would reassign parameters inside method call original variables passed to the method would not change.