Kotlin switch 2 integers


#1

Hello,
I would like switch 2 integers. With Java I could do that thank to :
void switch( int &a, int &b){ int memory = a; a = b; b = a; }

but how can I do that with kotlin
thanks for your help


#2

This code is not Java. And your code does not work. Please take some time to ensure that your question is clear and correct before posting. Thank you.


#3

yes, i did an error when I copied :
void change( int &a, int &b){ int memory = a; a = b; b = memory; }


#4

Still not Java.

But to answer your question: This is not possible in Kotlin unless you wrap Ints with a mutable wrapper:

class MutableInt(var value: Int)

fun switch(a: MutableInt, b: MutableInt) {
    val memory = a.value
    a.value = b.value
    b.value = memory
}

#5

First, this:

void change( int &a, int &b){ int memory = a; a = b; b = memory; }

as far as I can tell is C++ not Java.

Unless I am mistaken, Java equivalent would be:

static void change(Integer a, Integer b) {
  Integer memory = a;
  a = b; 
  b = memory;
}

And in Kotlin (since Int? is stored as Integer and not primitive int: https://kotlinlang.org/docs/reference/basic-types.html):

static void change(Int? a, Int? b) {
  val memory: Int? = a;
  a = b; 
  b = memory;
}

#6

Both of your code samples do not work, but for different reasons:

  • The Java version only changes the parameters a and b, but not the values they point to.
  • Parameters are immutable in Kotlin, so you cannot assign to them. And even if you could, you would have the same problem as with Java.

Please make sure your code samples are correct before posting. If in doubt, verify the behavior in a short prorgram before posting. Thank you.


#7

Thanks for pointing my mistakes. I’ll be more careful posting next time.


#8

thank you jstuyts it works


#9

I think this is simpler:

a = b.also { b = a}