There are two misunderstandings here:
First, in Kotlin all parameters are final
and this cannot be changed. Just as in Java a final
reference cannot be changed. So you get an error when trying to reassign a final
or val
reference.
Second, since you have a copy of a reference to a String, your swap function would have no affect on the caller's original references. Your swap function wouldn't work in Java either.
For example, calling your code does nothing:
val s1 = "howdy"
val s2 = "goodbye"
swap(s1,s2) // Java or Kotlin, doesn't matter
println(s1)
println(s2)
// output:
// howdy
// goodbye
And definitely calling it with literals or expressions does nothing:
swap("happy","day") // what references is it supposed to be swapping?
You can only swap the contents inside of an object for which you hold the same reference as the caller. To make a swap routine, you would do something like:
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
}
Which you could call:
val stringies = MutablePair("howdy", "goodbye")
println("${stringies.one} ${stringies.two}")
swap(MutablePair()
println("${stringies.one} ${stringies.two}")
// output:
// howdy goodbye
// goodbye howdy
swap
function won't do anything at all.swap(9, 42)
. This assignment may look confusing, and thus prohibited in Kotlin.