Immutability in Kotlin

Immutability in Kotlin is a core concept in Kotlin that ensures once a variable or collection is initialized, its value or contents cannot be changed. This promotes safer and more predictable code, especially in concurrent programming environments and functional programming paradigms. In Kotlin, immutability is enforced through the use of val and var keywords for variables, and through immutable collections.

val vs var

In Kotlin, variables can be declared using val (immutable) or var (mutable):

  • val: Variables declared with val are immutable; their value cannot be changed after initialization.
  • var: Variables declared with var are mutable; their value can be reassigned.

Example with val:

Kotlin
val pi = 3.14
// pi = 3.14159 // Error: Val cannot be reassigned

Example with var:

Kotlin
var counter = 0
counter += 1 // Mutable variable can be reassigned

Immutable Collections

Kotlin provides immutable collections for lists, sets, and maps. These collections are created using functions like listOf, setOf, and mapOf, ensuring that their contents cannot be modified once initialized.

Example with List:

Kotlin
val numbers = listOf(1, 2, 3, 4, 5)
// numbers.add(6) // Error: Immutable list cannot be modified

Example with Map:

Kotlin
val userInfo = mapOf(
    "name" to "John",
    "age" to 30,
    "email" to "[email protected]"
)
// userInfo["name"] = "Jane" // Error: Immutable map cannot be modified

Real-World Example: Product Catalog

Let’s consider a scenario where you have a product catalog in an e-commerce application. The product information should remain constant once loaded.

Kotlin
data class Product(val id: Int, val name: String, val price: Double)

val products = listOf(
    Product(1, "Phone", 599.99),
    Product(2, "Laptop", 1299.99),
    Product(3, "Headphones", 99.99)
)

// Attempting to modify the list after creation (immutability) - this will result in errors
// products.add(Product(4, "Tablet", 399.99)) // Error: Immutable list cannot be modified

for (product in products) {
    println("ID: ${product.id}, Name: ${product.name}, Price: $${product.price}")
}

Output:

Kotlin
ID: 1, Name: Phone, Price: $599.99
ID: 2, Name: Laptop, Price: $1299.99
ID: 3, Name: Headphones, Price: $99.99

In this example, the products list is immutable, containing information about various products. Attempting to modify the list (e.g., adding a new product) after its creation results in compilation errors, ensuring the integrity of the product catalog.

Understanding and leveraging immutability in Kotlin with val vs var for variables and immutable collections provides a robust foundation for writing reliable and maintainable code. By embracing immutability, developers can create safer and more predictable software systems.