Open In App

How to Write swap Function in Kotlin using the also Function?

Last Updated : 23 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

also is an extension function to Template class which takes a lambda as a parameter, applies contract on it, executes the lambda function within the scope of calling object, and ultimately returns the same calling object of Template class itself. Swapping two numbers is one of the most common things you do in programming. Most of the approaches are quite similar in nature: Either you do it using a third variable or using pointers. In Java, we don’t have pointers, so mostly we rely on a third variable. You can obviously use something as mentioned here, which is just the Kotlin version of Java code:

Kotlin




var a = 1
var b = 2
run { val temp = a; a = b; b = temp }
println(a) // print 2
println(b) // print 1


However, in Kotlin, there is a very quick and intuitive way of doing it. Let’s see how!

Example

In Kotlin, we have a special function, BMTP, that we can use to swap two numbers. Here’s the code to go with it:

Kotlin




var a = 1
var b = 2
a = b.also { b = a }
println(a) // print 2
println(b) // print 1


We were able to achieve the same thing without using any third variable.

To understand the preceding example, we need to understand the also function in Kotlin. The also function takes the receiver, performs some operation, and returns the receiver. In simple words, it passes an object and returns the same object. Applying the also function on an object is like saying “do this as well” to that object. So, we called the also function on b, did an operation (assigning the value of a to b), and then returned the same receiver that we got as an argument:

Kotlin




var a = 1
var b = 2
a = b.also{
  b = a
  // prints it=2:b=1:a=1
  printIn("it=$it : b=$b : a=$a"
  }
printIn(a) // print 2
printIn(b) // print 1


The apply function is quite similar to the also function, but they have a subtle difference. To understand that, let’s look at their implementation first:

also function:

Kotlin




public inline fun <T> T.also(block: (T) -> Unit): T{ block(this);
return this }


apply function:

Kotlin




public inline fun <T> T.apply (block : T.()-> Unit ) : T {block()};
return this }


In also, the block is defined as (T) -> Unit, but it is defined as T. () -> Unit in apply (), which means there is an implicit this inside the apply block. However, to reference it in also, we need it. So a code using also will look like this:

val result = Dog (12) . also { it . age = 13 }

The same will look like this using apply:

val result2 =Dog (12) . apply (age = 13 }

The age of the resulting object will be the same in both cases, that is, 13.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads