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

1 Answer

0 votes
// Immutable User in Scala (Using Case Classes and Immutable Fields)

//
// Scala enforces immutability naturally:
//
// 1. `val` → immutable variable binding
// 2. `case class` → fields are immutable by default
// 3. No setters → no mutation path
// 4. Copy method → creates new modified instances without changing the original
//
// This makes Scala one of the strongest JVM languages for immutability.
//

// Immutable User using a case class
case class User(id: Int, name: String)

object Main {
  def main(args: Array[String]): Unit = {

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

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

    // Attempt 1: modify id
    // user.id = 100        // ERROR:  Reassignment to val id (fields are immutable)

    // Attempt 2: modify name
    // user.name = "Tim"    // ERROR: Reassignment to val name

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

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

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


/* 
run:

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

*/

 



answered 3 hours ago by avibootz
...