![]() |
VOOZH | about |
Swapping two numbers is one of the most common tasks in programming. Usually, when we swap two values in languages like Java or C++, we either use a third temporary variable or pointers/references to perform the swap. In Java, since we don’t have pointers, we almost always rely on a third variable to swap two numbers:
int temp = a;
a = b;
b = temp;This is simple and works perfectly but Kotlin offers a shorter, more elegant way to swap values without using any third variable. Let’s learn how!
Before we jump into the swap example, we need to understand the also function in Kotlin. The also function is an extension function available to all objects. It allows us to perform some operations on an object and then returns the same object.
Let’s look at the basic usage:
val dog = Dog(12).also {
// 'it' refers to the object itself it.age = 13 }
Here we have an object Dog(12). We used also to change its age to 13. The also function returns the same modified object.
Here’s how we can swap two numbers in Kotlin without using a third variable by using the also function.
Output:
a = 10
b = 5Let’s understand this step by step:
Now, we must wonder why does it work. Let's think of an expression.
a = b.also { b = a }The function also takes the value of b (which is 10). Inside the block { b = a }, we assign b = a (which is 5). So now b = 5. The original value of b (10) is returned by also, and this value gets assigned to a. Result: a = 10, b = 5. The numbers have swapped without using a temporary variable.
Many people often confuse the also and apply functions in Kotlin because they seem similar, but there is an important difference in how they handle the receiver object inside their lambda blocks. In the case of also, the receiver is accessed using the keyword it, and the function always returns the same receiver object after performing the specified operations. On the other hand, apply uses this as the receiver inside its block, and in fact, this is implicit, so you can refer to the object's properties and functions directly without needing to use any special keyword. Just like also, apply also returns the same receiver object after applying the changes.
Example with also function:
Example with apply function:
Both modify the same object and return the object itself, but in also, you must use it to refer to the object. In apply, you can use this (or nothing at all since it's implicit).