How to write a swap function in Kotlin using the also function
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:
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!
Getting ready
You need to install a preferred development environment that compiles and runs Kotlin. You can also use the command line for this purpose, for which you need Kotlin compiler installed, along with JDK. I am using IntelliJ IDE to compile and run my Kotlin code for this recipe.
How to do it...
In Kotlin, we have a special function, also
, that we can use to swap two numbers. Here's the...