In Kotlin, the also
function is used to perform an action on an object and then return that object. It takes a lambda expression as an argument, and the lambda expression is executed with the object as the receiver.
variable.also{ codeblock }
This code snippet can be broken down into the following steps:
- The
variable
is read and stored in a temporary variable. - The
codeblock
is executed. - The value stored in the temporary variable is returned.
In the case of the code snippet you provided, the variable
is b
, and the codeblock
is b = a
. This means that the value of b
is first stored in a temporary variable, then the value of a
is assigned to b
, and finally the value of the temporary variable is returned.
This code snippet can be used to swap the values of two variables. For example, the following code swaps the values of a
and b
:
var a = 1 var b = 2 a = b.also { b = a }
After this code is executed, the value of a
is 2 and the value of b
is 1.