Title here
Summary here
Kotlin has built-in support for multiple return values through data classes or Pair/Triple objects. This feature is often used in idiomatic Kotlin, for example, to return both result and error values from a function.
import kotlin.Pair
// The `Pair<Int, Int>` in this function signature shows that
// the function returns 2 `Int`s.
fun vals(): Pair<Int, Int> {
return Pair(3, 7)
}
fun main() {
// Here we use destructuring declaration to get the 2 different
// return values from the call.
val (a, b) = vals()
println(a)
println(b)
// If you only want a subset of the returned values,
// you can use an underscore for the values you don't need.
val (_, c) = vals()
println(c)
}
When you run this program, you’ll see:
3
7
7
In Kotlin, we use a Pair
to return multiple values from a function. The destructuring declaration feature allows us to easily assign these values to separate variables.
If you need to return more than two values, you can use a Triple
or create a custom data class.
Accepting a variable number of arguments is another nice feature in Kotlin; we’ll look at this next with vararg parameters.