0
0
Kotlinprogramming~5 mins

Why immutable collections are default in Kotlin

Choose your learning style9 modes available
Introduction

Immutable collections help keep data safe and predictable by not allowing changes after creation.

When you want to share data safely between different parts of your program without accidental changes.
When you want to avoid bugs caused by unexpected changes to your lists or maps.
When you want your program to be easier to understand because data does not change.
When you want to write code that is easier to test and debug.
When you want to improve performance by avoiding unnecessary copying or locking.
Syntax
Kotlin
val list = listOf("apple", "banana", "cherry")
val map = mapOf("a" to 1, "b" to 2)

listOf() and mapOf() create immutable collections.

Immutable collections do not have methods to add or remove items.

Examples
This creates an immutable list of fruits. You cannot add or remove items later.
Kotlin
val fruits = listOf("apple", "banana", "cherry")
This creates an immutable set of numbers with no duplicates allowed.
Kotlin
val numbers = setOf(1, 2, 3)
This creates an immutable map linking names to ages.
Kotlin
val ages = mapOf("Alice" to 30, "Bob" to 25)
Sample Program

This program creates immutable collections and prints them. Trying to change them causes errors.

Kotlin
fun main() {
    val fruits = listOf("apple", "banana", "cherry")
    println("Fruits: $fruits")

    // The following line would cause a compile error because the list is immutable
    // fruits.add("date")

    val ages = mapOf("Alice" to 30, "Bob" to 25)
    println("Ages: $ages")
}
OutputSuccess
Important Notes

Immutable collections help avoid accidental changes that cause bugs.

If you need to change a collection, use mutable versions like mutableListOf().

Immutable collections are thread-safe because they cannot be changed.

Summary

Immutable collections do not allow changes after creation.

They make programs safer and easier to understand.

Use listOf(), setOf(), and mapOf() to create immutable collections in Kotlin.