Notification texts go here Contact Us Buy Now!

In Kotlin, How does the following code snippet work to swap variables values?

variable.also{ codeblock }
as
  1. read the variable and store it in a temporary variable
  2. execute the codeblock
  3. return what you stored in step 1.
So in your case it's
  1. read b (which has value 2) and store it in a temporary variable
  2. execute the b = a. meaning that 1 is assigned to the variable b.
  3. return what you stored in step 1, which is the value 2.
  4. 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 with this value as its argument and returns this value.

From that, we can note the following things:

  1. It is an extension function (thus has a receiver).

  2. It is an inline function.

  3. Its argument is a function type, which:

    • Accepts the receiver as an argument.

    • Will also be inlined.

  4. 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.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.