The also that you may not get noticed
Recently, I found that we can just use also
to swap two variables directly in one line (stack overflow). The code is like below
var a = 1000
var b = 2000
a = b.also { b = a }
println(a) // print 2000
println(b) // print 1000
If we read the line a = b.also { b = a }
assigning b to a and also assigning a to b
It is very straightforward but I got confused when I first saw it. Because b
is changed in the also
, a
and b
should be the same. Why can it swap those two variables?
The implementation of also
if we check the implementation of also
.
public inline fun <T> T.also(block: (T) -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block(this)
return this
}
The return value is this
. Apparently, the this
and b
are different in this expression a = b.also { b = a }
, why?
The “it” parameter
The lambda in Kotlin has a feature: If the lambda only has one parameter, it
is the implicit name of the parameter.
If we rewrite the expression with explicit variable name like below, it is more easier to understand.
a = b.also { temp ->
b = a
}
It just looks like how we implement swapping two variables in the traditional way, isn’t it?
Now we can understand easily that temp
is the original b
in the also
block. So the way we change b
in the also
would not pollute the original value.
Summary
Kotlin’s stdlib has comprehensive functions to help developers to write a concise code more easily. For example, we can just swap the two variables in one line with the help of also
. That’s amazing!