Swap Function in Kotlin

If you want to write some really scary code, you could have a function like this:

inline operator fun <T> T.invoke(dummy: () -> Unit): T {
    dummy()
    return this
}

That would allow you to write code like this

a = b { b = a }

Note that I do NOT recommend this. Just showing it's possible.


Edit: Thanks to @hotkey for his comment

I believe the code for swapping two variables is simple enough - not to try simplifying it any further.

The most elegant form of implementation IMHO is:

var a = 1
var b = 2

run { val temp = a; a = b; b = temp }

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

Benefits:

  • The intent is loud and clear. nobody would misunderstand this.
  • temp will not remain in the scope.

No need a swap function in Kotlin at all. you can use the existing also function, for example:

var a = 1
var b = 2

a = b.also { b = a }

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

Tags:

Kotlin