1

I'm new to Kotlin and I don't know where I went wrong with this.

fun swap(a:Int,b:Int):Unit{
    a=a xor b
    b=b xor a
    a=a xor b
}

fun main() {
    var a =10
    var b = 1000
   // swap(a, b)
    //print("$a, %b")
}

I get these errors.enter image description here Thanks!

I was trying to use

ref

key word but it doesn't work

  • You cannot do this to local properties declared in a function. For other properties, you can take a `KMutableProperty0` and replace the assignments and accesses with `set` and `get`. Either way, [there are much better ways to write a `swap`](https://stackoverflow.com/q/45377802/5133585). – Sweeper Aug 30 '23 at 09:57

1 Answers1

1

I am no expert to Kotlin, but I'd say you can't achieve this in the way you wrote it.

Check out this answer to question Is Kotlin "pass-by-value" or "pass-by-reference"?. In short, the parameters your function retrieves are passed-by-value and, as such, cannot be swapped. They're not your C pointers.

Now, another answer on StackOverflow explains why you don't even need a swap function in Kotlin and how you can implement the swapping behavior:

var a = 1
var b = 2

a = b.also { b = a }

println(a) // print 2
println(b) // print 1

Now if you really want to implement a swap function, since the JVM world is pass-by-value, you could implement a wrapper to wrap your integers, something like:

// NOTE You have to use "var" not "val".
data class IntWrapper(var value: Int)

fun swap(a: IntWrapper, b: IntWrapper) {
    a.value = a.value xor b.value
    b.value = b.value xor a.value
    a.value = a.value xor b.value
}

Check out working example.

Victor
  • 13,914
  • 19
  • 78
  • 147