Kotlin Tip #10: Prefer Immutable Collections — 100 Kotlin Tips in 100 Days

Raphael De Lio
Kotlin with Raphael De Lio
3 min readFeb 19, 2024

Twitter | LinkedIn | YouTube | Instagram
Tip #9: Utilize Higher-Order Functions

The first Kotlin tip was about giving preference to val over var. This means we should give preference to immutable variables which refers to the concept of creating collections that cannot be modified after their creation. This concept offers advantages such as thread safety, easier debugging, and reduced side effects.

Java 9 introduced factory methods for creating immutable collections (List.of(), Map.of(), Set.of()), which was a step in the right direction, but for many years, Java developers had to either accept the verbosity or bring in additional libraries like Guava to simplify immutable collection creation.

Kotlin recognizes the challenges associated with mutable states right in its core and offers a concise and elegant way to work with immutable collections through listOf(), mapOf(), and setOf() functions. These functions create immutable instances of lists, maps, and sets, aligning with the language’s emphasis on safety and simplicity.

val immutableList = listOf(1, 2, 3)
val immutableMap = mapOf(1 to "One", 2 to "Two")
val immutableSet = setOf("a", "b", "c")

By making immutability the easy path, Kotlin encourages practices that lead to more robust and maintainable code. Moreover, the concise syntax makes codebases more approachable and easier to understand.

// Kotlin allows chaining and transformations directly on immutable collections
val modifiedList = listOf(1, 2, 3).map { it * 2 }.filter { it > 3 }

This simplicity does not sacrifice flexibility. Kotlin provides a clear distinction between mutable and immutable collections (e.g., mutableListOf() vs listOf()), allowing developers to explicitly choose mutability when they need it.

fun main() {
// Creating an immutable list using listOf
val immutableList = listOf("Apple", "Banana", "Cherry")
// Trying to add a new item to the immutable list will cause a compilation error
// immutableList.add("Date") // Uncommenting this line will result in a compile-time error

// Creating a mutable list using mutableListOf
val mutableList = mutableListOf("Apple", "Banana", "Cherry")
// Adding a new item to the mutable list is allowed
mutableList.add("Date")
}

While there are scenarios where mutable collections are necessary, opting for immutability as the default choice can lead to numerous long-term benefits in software development. It’s a great exercise to challenge yourself and try to use immutable collections, and the rich number of manipulation functions provided by the language, where it may seem difficult in the first place.

Let’s implement together a program whose goal is to calculate the total sales amount for each month from a list of sales transactions. This operation involves grouping the sales by month, calculating the total sales per month, and then presenting this information in a structured way.

It may be intuitive to try to solve this problem by using a mutable map, like in the example below:

However, if we challenge ourselves, we can come up with a much simpler solution by leveraging Kotlin’s immutable collection and the provided wide number of manipulation functions:

This approach not only ensures immutability but also leverages Kotlin’s collection processing capabilities to make the code more concise, readable, and less prone to errors associated with mutable states.

I hope you have enjoyed the tenth tip of our series! Don’t forget to subscribe and stay tuned for more Kotlin tips!

Stay curious!

Tip #11: Prefer Data Classes for Classes Meant to Hold Data

Contribute

Writing takes time and effort. I love writing and sharing knowledge, but I also have bills to pay. If you like my work, please, consider donating through Buy Me a Coffee: https://www.buymeacoffee.com/RaphaelDeLio

Or by sending me BitCoin: 1HjG7pmghg3Z8RATH4aiUWr156BGafJ6Zw

Follow Me on Social Media

Stay connected and dive deeper into the world of Kotlin with me! Follow my journey across all major social platforms for exclusive content, tips, and discussions.

Twitter | LinkedIn | YouTube | Instagram

--

--