How to Write swap Function in Kotlin using the also Function?
Last Updated :
23 Jan, 2022
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.
Similar Reads
How to Specify Default Values in Kotlin Functions? In Kotlin, you can provide default values to parameters in a function definition. If the function is called with arguments passed, those arguments are used as parameters. However, if the function is called without passing argument(s), default arguments are used. But If you come from the Java world,
4 min read
Transform a List Using Map Function in Kotlin Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 and is a new language for the JVM. Kotlin is an object-oriented language, and a âbetter
3 min read
Working with Anonymous Function in Kotlin In Kotlin, we can have functions as expressions by creating lambdas. Lambdas are function literals that is, they are not declared as they are expressions and can be passed as parameters. However, we cannot declare return types in lambdas. Although the return type is inferred automatically by the Kot
3 min read
Passing Variable Arguments to a Function in Kotlin There are a lot of scenarios in which we need to pass variable arguments to a function. In Kotlin, You can pass a variable number of arguments to a function by declaring the function with a vararg parameter. a vararg parameter of type T is internally represented as an array of type T ( Array<T
4 min read
How to Pass a Function as a Parameter to Another in Kotlin? Kotlin gives us the power to declare high-order functions. In a high-order function, we can pass and return functions as parameters. This is an extremely useful feature and makes our code much easier to work with. In fact, many of the Kotlin library's functions are high order, such as NBQ. In Kotlin
4 min read
How to Send SMS in Android using Kotlin? SMS Manager is a class in Android which is used to send the SMS to a specific contact from the android application. We can send text messages, data messages, and multimedia messages using this class. There are different methods that are provided to send different types of messages. In this article,
4 min read
How to Get the Class in Kotlin? Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 and is a new language for the JVM. Kotlin is an object-oriented language, and a âbetter
3 min read
Kotlin Function Variations With Examples While defining a function in Kotlin we have many optional annotations. We will learn each of them one by one. Defining a function in Kotlin: Visibility modifier fun functionName (argument name: type name, ...): return type{ ..... // function body ..... return value } Normally, It is the proper way f
3 min read
Kotlin Collection Write operations Collection Write operations are used to change the content of MutableCollection. MutableCollection is defined as the Collection with write operations like add and remove. Operations supported are as follows: Adding elements Removing elements and Updating elements Addition of elements - add() functio
4 min read
What is Flow in Kotlin and How to use it in Android Project? To build an app asynchronously we have to use RxJava and it is also one of the most important topics in Android Development. But now in Kotlin Jetbrains came up with Flow API. With Flow in Kotlin now we can handle a stream of data sequentially. Flow is a stream processing API in Kotlin developed by
4 min read