![]() |
VOOZH | about |
Kotlin is a statically typed, general-purpose programming language created by JetBrains, the company that also built world-famous IDEs like IntelliJ IDEA, PhpStorm, and AppCode. Kotlin was first introduced by JetBrains in 2011 and is designed to run on the Java Virtual Machine (JVM). Kotlin is an object-oriented language that is often considered "better than Java" in many ways, while still being fully compatible with existing Java code. In this article, we will learn how to return multiple values from a function in Kotlin.
Before we start, let’s quickly recall that when we declare a function, it performs a specific task and usually returns only one value. However, sometimes we want to return more than one value from a function. Kotlin gives us several ways to do this.
Suppose we want to calculate both the positive and the negative square roots of a given integer. One way to solve this is by writing two separate functions:
But calling two separate functions for a single task seems unnecessary and not very clean.
We can return an array containing both the positive and negative roots:
This method works, but there is one problem, we do not know which value is at which position just by looking at the return type. Is the positive root at index 0 or index 1? Without checking the function’s code or its documentation, we can’t be sure.
We can make this clearer by defining our own class with named properties:
Now it is easy to understand the result:
val result = roots2(16)
println("Positive Root: ${result.positive}")
println("Negative Root: ${result.negative}")
This way, we clearly know which value is positive and which is negative.
If creating a new class feels like too much for a small task, we can use Kotlin's built-in Pair class:
And we can use it like this:
val result = roots3(16)
println("Positive Root: ${result.first}")
println("Negative Root: ${result.second}")
But this approach has the same small problem as the array, we have to remember which is .first and which is .second. When the purpose of the values is very clear (like currency and amount), this is acceptable. Otherwise, using a class with named fields is better.
If we wanted to return three values, Kotlin also provides a built-in Triple class:
Just like Pair, we can access the values using .first, .second, and .third.
Kotlin also allows us to destructure pairs, triples, or data classes easily at the calling site:
val (pos, neg) = roots3(16)
println("Positive Root: $pos")
println("Negative Root: $neg")
Notice how clean this looks. The first value is automatically assigned to pos, and the second to neg. Destructuring works for: