Immutability
Learn about the concept of immutability in Kotlin.
Functional programming has been around for as long just as other programming paradigms, for example, procedural and object-oriented programming. But in the past 15 years, it has gained significant momentum. The reason for this is that something else stalled: CPU speeds. We cannot speed up our CPUs as much as we did in the past, so we must parallelize our programs. And it turns out that the functional programming paradigm is exceptionally good at running parallel tasks.
One of the fundamental concepts of functional programming is immutability. This means that from the moment the function receives input to the moment the function returns output, the object doesn’t change. But how could it change? Well, let’s look at a simple example. The following code would output a
first, and then we’d receive ConcurrentModificationException
. Run the following code to see the result:
import java.util.*fun main() {// Will cause ConcurrentModificationExceptionprintAndClear(mutableListOf("a", "b", "c"))val firstEdition = Triple("Design Patterns with Kotlin", 310, 2018)}private fun <T> printAndClear(list: MutableList<T>) {for (e in list) {println(e)list.remove(e)}}
The reason for this is that the for
loop uses an iterator, and by mutating the list inside the loop, we interfere with its ...
Get hands-on with 1400+ tech skills courses.