Immutability
One of the key concepts of functional programming is immutability. It means that from the moment the function receives input to the moment the function returns output, the object doesn't change. How could it change, you wonder? Let's see a simple example:
fun <T> printAndClear(list: MutableList<T>) { for (e in list) { println(e) list.remove(e) } } printAndClear(mutableListOf("a", "b", "c"))
The output would be first "a"
, then we'll receive ConcurrentModificationException
.
Wouldn't it be great if we could protect ourselves from such runtime exceptions in the first place?
Tuples
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 work pair.second = 2 // Still doesn't
We can destructure a Pair into two separate values:
val (key, value) = pair println("$key ...