Kotlin Training Program

DOWNLOAD APP

FEEDBACK

Swap

Swapping values of two variables refers to interchanging their values.

Example :

 // Before swapping
a = 2, b = 3

// After swapping
b = 3, a = 2
 

This is required in other algorithms like String#replace() and List#sort().

There are three ways to perform this action :

Using temporary variable

We can use a temporary variable to store the value of one of the variables before assigning it the value of second variable. Following is the algorithm to swap two variables a & b using temp as the temporary variable :

Implementation

 fun main() {
    var a = 2; var b = 3
    println("Before swapping: a=$a, b=$b")

    // Swap
    val temp = a
    a = b
    b = temp

    println("After swapping: a=$a, b=$b")
}

/* Output :

Before swapping: a=2, b=3
After swapping: a=3, b=2
 */
 

Using also() function

Recall that also() is a scope function takes a lamda as argument and returns the same object after executing the lambda. The lambda receives the object as input parameter.

 fun <T> T.also(block: (T) -> Unit): T
 

We can use this function to swap two variables :

 a = b.also{ b = a }
 

Firstly, the lambda is executed which assigns a’s value to b. Then b’s initial value is assigned to a. You might think that if b is assigned a’s value first then how is b’s previous value assigned to a, now that it has been changed. The magic lies in the also() function & the working of this keyword in Kotlin. It automatically creates a copy of object before executing the lambda and hence it is able to return the previous value.

Complete example :

 fun main() {
    var a = 2; var b = 3
    println("Before swapping: a=$a, b=$b")

    // Swap
    a = b.also { b = a }

    println("After swapping: a=$a, b=$b")
}

/* Output :

Before swapping: a=2, b=3
After swapping: a=3, b=2
 */
 

Using basic math

This technique works only for numbers. Using addition and subtraction, we can easily swap values of two numeric variables (say a & b) :

Example :

 fun main() {
    var a = 2; var b = 3
    println("Before swapping: a=$a, b=$b")

    // Swap
    a += b      // a = 2 + 3 = 5
    b = a - b   // b = 5 - 3 = 2
    a -= b      // a = 5 - 2 = 3

    println("After swapping: a=$a, b=$b")
}

/* Output :

Before swapping: a=2, b=3
After swapping: a=3, b=2
 */