Where Immutability Comes Into Play

Immutability is often a key feature of functional programming languages. Immutability helps to ensure that impure functions do not break pure functions by changing data “behind the back” of the pure functions.

For example, there is a first() function available for us on List that returns the first element in the list that matches some rule provided via a lambda expression:

data class Event(val id: Int)

fun main() {
  val events = listOf(Event(1), Event(5), Event(1337), Event(24601), Event(42), Event(-6))

  val leetEvent = events.first { it.id == 1337 }

  println(leetEvent)
}

We will explore first() in greater detail later in this chapter. It is an example of functional programming in Kotlin, where first() is a pure function that acts on its input (a List) and return its output (the first element for which the lambda expression returns true).

However, while first() is pure — because the authors of Kotlin ensured that it was — it is possible that the lambda expression might be impure and have side effects. In particular, we might get strange results if:

As a result, we try to use immutable objects where possible, to reduce the likelihood that we will make those sorts of mistakes.

This also helps a lot with parallel programming, where we are performing operations in parallel across multiple threads. Developers who have had to deal with thread safety before know full well how nasty it can be to track down “timing bugs” where changes from one thread affect another thread’s work. Pure functions and immutable objects make it easier to ensure thread safety, as one thread cannot readily affect another thread’s work.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.