variable.also{ codeblock }
as
- read the
variable
and store it in a temporary variable - execute the
codeblock
- return what you stored in step 1.
So in your case it's
- read
b
(which has value2
) and store it in a temporary variable - execute the
b = a
. meaning that1
is assigned to the variableb
. - return what you stored in step 1, which is the value
2
. - this value is then assigned to the variable
a
Here is the documentation of also
:
inline fun <T> T.also(block: (T) -> Unit): T
Calls the specified function
block
withthis
value as its argument and returnsthis
value.
From that, we can note the following things:
It is an extension function (thus has a receiver).
It is an inline function.
Its argument is a function type, which:
Accepts the receiver as an argument.
Will also be inlined.
It returns the receiver object.
That all means this:
fun swapDemo() {
var a = 42
var b = 117
a = b.also { b = a }
}
Is approximately the same as writing this:
fun swapDemo() {
var a = 42
var b = 117
// begin 'also'
val receiver = b
val it = receiver // the 'block' function's parameter (unused)
b = a // the 'block' function
// end 'also'
a = receiver // 'also' "returns"
}
Ignoring the it
variable (also see below), you can see this looks just like a "traditional" swap implementation, with receiver
functioning as the temporary variable.
Note that, from inspecting the byte code, writing the following:
a = b.also { _ -> b = a }
Instead of:
a = b.also { b = a }
Will cause the it
local variable to be omitted. At least in Kotlin 1.9.22.