In this article, we will see different ways to return multiple values from a function in Kotlin.
Using Pair:
As a first way, we can use the Pair to return multiple values from a function. Pair accepts two parameters which are the values that we want to store.
Following is the example:
fun calculate(): Pair<Int, String> {
// Perform calculations
val resultValue1 = 42
val resultValue2 = "Hello, World!"
return Pair(resultValue1, resultValue2)
}
fun main() {
val (value1, value2) = calculate()
println("Value 1: $value1")
println("Value 2: $value2")
}
Using Triple:
If you have a requirement of returning three values then you can use the Triple
to return three values from a function.
This function takes three parameters which are the values that we want to store or return to the caller.
fun calculate(): Triple<Int, String, Boolean> {
val resultValue1 = 42
val resultValue2 = "Hello, World!"
val resultValue3 = true
return Triple(resultValue1, resultValue2, resultValue3)
}
fun main() {
val (value1, value2, value3) = calculate()
println("Value 1: $value1")
println("Value 2: $value2")
println("Value 3: $value3")
}
Note: If you have any custom requirement where you want to return more than three values from a function, then you can use the List type or you can write your own custom Data class.