1. Overview

In this tutorial, we’ll learn about various ways used to write swap functions in Kotlin.

Generally, a swap function refers to a utility function that allows us to exchange the values of two variables. We’ll learn about swap functions using the following methods:

  • Swapping values of different vars
  • Using a Pair object
  • The also() scope function

2. Swapping Values of Different vars

The simplest use case is to directly swap two variables inline. This method involves swapping the values of two variables using a temporary variable:

var a = 1
var b = 2

val temp = a
a = b
b = temp
assertEquals(2, a)
assertEquals(1, b)

First, two variables a and b are declared and initialized, containing values 1 and 2. We then introduce a variable temp to store the original value of a temporarily before a is overwritten. The value of a is then assigned the value of b and this means a now holds the value that was originally b. Finally, b is assigned the value of temp which has the original value of a. This results in b now holding the value that was initially in a.

3. Using Pair

The standard Pair is a handy wrapper for two values. We can swap two variable’s values using a Pair instance. The idea is first create a Pair object using the two variables and then reassign them using the corresponding value from the Pair object:

var x = 100
var y = 200
                    
(x to y).apply {
    x = second
    y = first
}
assertEquals(200, x)
assertEquals(100, y)

In the above example, we used the apply() scope function to reassign a and b.

4. The also() Scope Function

The also() function maintains a reference to the original object the function is called upon. By using this, we can grab the initial value of b, reassign b to a, and then finally assign a to the original value of b:

var a = 1
var b = 2
a = b.also { b = a }
assertEquals(2, a)
assertEquals(1, b)

5. Conclusion

In this article, we learned three approaches to writing a basic swap function in Kotlin. We discussed directly swapping variables inline, using a Pair, and using the also() scope function to swap variable values.

As always, the full source code used in the article can be found over on GitHub.

Comments are closed on this article!