Multiple Return Values in Kotlin
Last Updated :
22 Feb, 2022
Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, App code, 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 language” than Java, but still be fully interoperable with Java code. In this article, we are going to discuss how to return multiple values, but before going ahead you should know some basic things as When we declare a function it performs a specific task and finally it may return a value that's the meaning of returning values. but generally, the function returns not more than one value, so we hope you know this kind of basic stuff, but in case you don't then please refer to this article Kotlin functions.
Example
Let's say we wanted to calculate both the positive and negative square roots of an integer. We could approach this problem by writing two different functions:
Kotlin
fun positiveRoot(k: Int): Double {
require(k >= 0)
return Math.sqrt(k.toDouble())
}
fun negativeRoot(k: Int): Double {
require(k >= 0)
return -Math.sqrt(k.toDouble())
}
Another approach might be to return an array so we only have to invoke one function:
Kotlin
fun roots(k: Int): Array<Double> {
require(k >= 0)
val root = Math.sqrt(k.toDouble())
return arrayOf(root, -root)
}
However, we do not know from the return type whether the positive root or negative root is at position 0. We will have to hope the documentation is correct; if not, inspect the source code. We could improve this further by using a class with two properties that wrap the return values:
Kotlin
class Roots(pos: Double, neg: Double)
fun roots2(k: Int): Roots {
require(k >= 0)
val root = Math.sqrt(k.toDouble())
return Roots(root, -root)
}
This has the advantage of having named fields so we could be sure which is the positive root and which is the negative root. An alternative to a custom class is using the Kotlin standard library Pair type. This type simply wraps two values, which are accessed via the first and second fields:
Kotlin
fun roots3(k: Int): Pair<Double, Double> {
require(k >= 0)
val root = Math.sqrt(k.toDouble())
return Pair(root, -root)
}
This is most often used when it is clear what each value means. For example, a function that returned a currency code and an amount would not necessarily need to have a custom class, as it would be obvious which was which. Furthermore, if the function were a local function, you might feel that creating a custom class would be an unnecessary boilerplate for something that will not be visible outside of the member function. As always, the most appropriate choice will depend on the situation.
Note: There exists a three-value version of the pair, which is appropriately named triple.
We can improve this further by using destructuring declarations on the caller site. Destructuring declarations allow the values to be extracted into separate variables automatically:
val (pos, neg) = roots3 (16)
Notice that the variables are contained in a parenthesis block; The first value will be assigned to the positive root, and the second value will be assigned to the negative root. This syntactic sugar works with any object that implements a special component interface. The built-in Pair type, and all data classes, automatically implement this interface.
Similar Reads
What is Kotlin Multiplatform?
Kotlin Multiplatform or KMP is a technology that allows you to write code once and run it anywhere natively. This native feature motivates developers to prefer KMP over other cross-platform frameworks. KMP supports mobile operating systems such as Android and IOS, web, and desktop operating systems
5 min read
"lateinit" Variable in Kotlin
In Kotlin, there are some tokens that cannot be used as identifiers for naming variables, etc. Such tokens are known as keywords. In simple words, keywords are reserved and have special meaning to the compiler, hence they can't be used as identifiers. For example, asbreakclasscontinuelateinit "latei
3 min read
Kotlin | Plus and minus Operators
In Kotlin, working with collections like lists, sets, and maps is made easier and more readable thanks to operators like + (plus) and â (minus). These operators help you combine or remove elements from collections in a very natural way, just like doing math, but with objects instead of numbers.Worki
2 min read
lateinit vs lazy Property in Kotlin
Kotlin is a modern-day gem that has proved itself to be a very useful language for android developers. It comes up with features that are easy to use and most importantly very understandable for developers of any background, be it Java, JavaScript, or even those who're just beginning to explore Andr
3 min read
Triple in Kotlin
In programming, we call functions to perform a particular task. The best thing about function is that we can call it any number of times and it returns some value after computation i.e. if we are having add() function then it always returns the sum of both the numbers entered. But, functions have so
4 min read
Overriding Rules in Kotlin
In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. You decided your new class has to redefine one of the methods inherited
3 min read
Named Parameters in Kotlin
A parameter is a value that you can pass to a method. Then the method can use the parameter as though it were a local variable initialized with the value of the variable passed to it by the calling method. Function parameters are defined using Pascal notation - name: type. Parameters are separated u
3 min read
Parallel Multiple Network Calls Using Kotlin Coroutines
Application's home screen is where we need to populate multiple views like Promotional banners, List to show core content of the app, Basic user info, etc., It is really easy to fill all these views with data when you get all the required data in a single API call, but that's, not the case every tim
3 min read
Returns, Jumps and Labels 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 a new language for the JVM. Kotlin is an object-oriented language, and a âbetter lan
3 min read
Multiconditional Loop in Kotlin
As we all know about loops, in Kotlin, loops are compiled down to optimized loops wherever possible. For example, if you iterate over a number range, the bytecode will be compiled down to a corresponding loop based on plain int values to avoid the overhead of object creation. Conditional loops are c
3 min read