Notification texts go here Contact Us Buy Now!

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

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:

  1. The variable is read and stored in a temporary variable.
  2. The codeblock is executed.
  3. 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.

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.