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

Here in a fun exchange, I am trying to change the value of a1 from b1, but it shows that "val cannot be reassigned to a compile-time error". If I can’t change that, then how can this be done?

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

Note. This is just an example to understand why I cannot reassign a local variable, how can we do this in Java.

+19
source share
3 answers

Kotlin valdeclares the final, read-only, link - and that’s exactly what the compiler message tells you with

Val cannot be reassigned

val . , var

Kotlin final val, , Java.

, . , , , ( , Java). , , , .

+30

:

-, final, . Java, final . final val .

-, String, . Java.

, :

val s1 = "howdy"
val s2 = "goodbye"
swap(s1,s2)   // Java or Kotlin, doesn't matter
println(s1)
println(s2)

// output:
// howdy
// goodbye

:

swap("happy","day")  // what references is it supposed to be swapping?

, , . , - :

data class MutablePair(var one: String, var two: String)

fun swap(pair: MutablePair) {  // not thread safe       
   val temp = pair.one
   pair.one = pair.two
   pair.two = temp
}

:

val stringies = MutablePair("howdy", "goodbye")
println("${stringies.one} ${stringies.two}")
swap(MutablePair()
println("${stringies.one} ${stringies.two}")

// output:
// howdy goodbye
// goodbye howdy
+6

, :

fun swap(a1: String, b1: String) {
    val a1Swapped = b1
    val b1Swapped = a1
}
0

Source: https://habr.com/ru/post/1677978/


All Articles