Kotlin Function Return Multiple Values (Tuple)

May 14, 2019
Destructuring Declarations Example

Refer to Destructuring Declarations.

Pair

Return 2 values

fun returnPair() = Pair(1, "Desmond")
val (index, name) = returnPair()

val finalIndex = index + 1

NOTE: Destructuring variables (index, name) type is cast correctly

NOTE: Use underscore if you don’t need the variable: val (_, name) = returnPair()

Triple

Return 3 values

fun returnTriple() = Triple(1, "Desmond", true)
val (index, name, isActive) = returnTriple()

NOTE: Destructuring variables type is cast correctly

List or Array (up to 5 items)

Return multiple variables with list/array

fun returnArray() = arrayOf(1, "Desmond", true, 9.0, null)
val (index, name, isActive, score, item5) = returnList()

if (index as Int) {

}

val finalIndex = index as Int

NOTE: Destructuring variables are returned as Any

NOTE: If array/list length is less than deconstrucred variable, you will bump into java.lang.ArrayIndexOutOfBoundsException

NOTE: Max 5 deconstructed variables. If you try to deconstruct into 6 variables, you shall bump into Destructuring declaration initializer of type Array<Any?> must have a 'component6()' function.

Data Class

data class Result(val index: Int, val name: String, val isActive: Boolean, val score: Double, val item5: String?, val item6: String?)

fun returnDataClass() = Result(1, "Desmond", true, 9.0, null, "item6")
val (index: Int, name, isActive, score, _, item6) = returnDataClass()

NOTE: Destructuring variables type is cast correctly.

NOTE: More than 5 deconstructed variables.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.