ListsIntroduction to KotlinWriting functionsPairs and triples

Pairs and triples

Kotlin doesn't support arbitrary tuples like Python, but it has pairs and triples:

>>> var a = Pair(3, 5.0)
Note the type: the first element of pair a is an Int, the second one a Double. You can assign only pairs of the correct type to the variable a:
>>> a = Pair(3, 5)
error: type inference failed. Expected type mismatch: inferred type is kotlin.Pair<kotlin.Int, kotlin.Int> but kotlin.Pair<kotlin.Int, kotlin.Double> was expected
>>> a = Pair(2, 7.9)

You can access the elements of a pair or triple as the properties first, second, third:

>>> a.first
>>> a.second

You can also "unpack" a pair or triple like in Python:

val (x,y) = a
The parentheses around x and y are required.

Like in Python, tuples are often used if you want to return more than one value from a function:

>>> fun unpackYYMMDD(n: Int): Triple<Int, Int, Int> {
...   return Triple(n / 10000, (n / 100) % 100, n % 100)
... }
>>> unpackYYMMDD(20170315)
(2017, 3, 15)

You can assign the results directly to separate variables:

val (y, m, d) = unpackYYMMDD(20170315)
ListsIntroduction to KotlinWriting functionsPairs and triples