0
0
Kotlinprogramming~5 mins

Why immutability by default matters in Kotlin

Choose your learning style9 modes available
Introduction

Immutability means values cannot change once created. This helps avoid mistakes and makes programs easier to understand and safe.

When you want to keep data safe from accidental changes.
When multiple parts of a program use the same data without interfering.
When you want your program to be easier to test and debug.
When working with multiple threads to avoid conflicts.
When you want to write clear and predictable code.
Syntax
Kotlin
val name: String = "Alice"  // Immutable variable
var age: Int = 30               // Mutable variable

val creates an immutable variable that cannot be changed after assignment.

var creates a mutable variable that can be changed later.

Examples
You cannot change a val once set.
Kotlin
val greeting = "Hello"
// greeting = "Hi"  // This will cause a compile error
var allows changing the value.
Kotlin
var counter = 0
counter = 1  // This is allowed because counter is mutable
Immutable collections cannot be changed after creation.
Kotlin
val list = listOf(1, 2, 3)
// list.add(4)  // Error: list is immutable
Mutable collections can be changed.
Kotlin
val mutableList = mutableListOf(1, 2, 3)
mutableList.add(4)  // This works because the list is mutable
Sample Program

This program shows how val and var work. Trying to change val causes an error, but var can be changed.

Kotlin
fun main() {
    val name = "Bob"
    // name = "Alice"  // Uncommenting this line causes an error

    var age = 25
    println("Name: $name, Age: $age")

    age = 26  // Changing mutable variable
    println("Updated Age: $age")
}
OutputSuccess
Important Notes

Using val by default helps prevent bugs caused by unexpected changes.

Immutability makes your code easier to read and reason about.

Mutable variables (var) should be used only when necessary.

Summary

Immutability means values cannot change after creation.

Kotlin uses val for immutable and var for mutable variables.

Using immutability by default makes code safer and easier to understand.