June 2018
Intermediate to advanced
310 pages
6h 32m
English
In functional programming, a tuple is a piece of data that cannot be changed after it is created. One of the most basic tuples in Kotlin is Pair:
val pair = "a" to 1
Pair contains two properties, first and second, and is immutable:
pair.first = "b" // Doesn't workpair.second = 2 // Still doesn't
We can destructure a Pair into two separate values:
val (key, value) = pairprintln("$key => $value")
When iterating over a map, we receive another tuple, Map.Entry:
for (p in mapOf(1 to "Sunday", 2 to "Monday")) { println("${p.key} ${p.value}")}
In general, data classes are usually a good implementation for tuples. But, as we'll see in the Value Mutation section, not every data class is a proper tuple.
Read now
Unlock full access