0

I have a method which swaps the value of two variables.

void switchValue(int* a , int* b){
      //logic here...
}

C++ works on a lower level than Kotlin but can I do this on Kotlin?

daniel.jbatiz
  • 437
  • 4
  • 18
John.Staff
  • 53
  • 6

1 Answers1

3

It's impossible to do this with a function in Kotlin or Java, because references can only be passed by value. (Unless you're satisfied with using a wrapper class and you swap what two wrapper instances are referencing, but this would be clumsy.)

This is probably the easiest way to swap two variables' values:

var x = 0
var y = 1

//swap:
x = y.also { y = x }

Edit: A bit of correction. You can sort of do it with properties using reflection. This wouldn't work on local variables, though.

fun <T> swap(first: KMutableProperty0<T>, second: KMutableProperty0<T>) {
    first.set(second.get().also { second.set(first.get()) })
}

swap(::x, ::y)

In my opinion, this kind of practice (remotely changing variable values), although common in C/C++, should be avoided.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154