How to enforce immutability to prevent the modification of values in Kotlin

1 Answer

0 votes
// Immutable User in Kotlin (Using val + Data Classes for True Immutability)

//
// Kotlin enforces immutability through:
//
// 1. `val` → prevents reassignment of variables
// 2. `data class` → fields are immutable unless declared `var`
// 3. No setters → no mutation path
// 4. `copy()` → creates new modified instances without altering the original
//

// Immutable User using a data class (all fields are val)
data class User(val id: Int, val name: String)

fun main() {

    // Immutable user
    val user = User(42, "Sophia")

    println("ID: ${user.id}")
    println("Name: ${user.name}")

    // Attempt 1: modify id
    // user.id = 100        // ERROR: 'val' cannot be reassigned.

    // Attempt 2: modify name
    // user.name = "Tom"    // ERROR: 'val' cannot be reassigned.

    // Instead, Kotlin uses copy() to create a new modified instance
    val updatedUser = user.copy(name = "Tom")

    println("Updated Name (new instance): ${updatedUser.name}")

    // Original remains unchanged
    println("Original Name: ${user.name}")
}



/* 
run:

ID: 42
Name: Sophia
Updated Name (new instance): Tom
Original Name: Sophia

*/

 



answered 2 hours ago by avibootz
...