Swap Function in Kotlin

2019-03-22 16:09发布

问题:

is there any better way to write generic swap function in kotlin other than java way described in How to write a basic swap function in Java.

Is there any kotlin language feature which can make generic swap function more concise and intuitive?

回答1:

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


回答2:

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.



回答3:

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.


回答4:

Kotlin encourages the use of immutable data when possible (such as using val instead of var). This greatly reduces the change for subtle bugs, since it's possible to reason more soundly about code if values don't change.

Swapping two values is very much the opposite of immutable data: Did I mean the value of a before or after the swap?

Consider rewriting your code in the following immutable way:

val a = 1
val b = 2

val (a2, b2) = b to a

This works by making use of destructuring declarations, along with the built-in to extension function that creates a Pair.



回答5:

That is a good usage for with:

var a = 1
var b = 2

with(a) {
    a = b
    b = this
}

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


标签: kotlin