Case Classes and Pattern Matching
Copy and Update
Make a changed copy without mutating the original.
Copy and Update
CopyUpdate.scala
case class Account(owner: String, balance: Int)
object Main {
def main(args: Array[String]): Unit = {
val deposit =
val base = Account("Ann", 100)
val balance = base.balance + deposit
val updated = base.copy(balance = balance)
println("owner=" + updated.owner)
println("oldBalance=" + base.balance)
println("newBalance=" + updated.balance)
}
}
case class Account(owner: String, balance: Int)
object Main {
def main(args: Array[String]): Unit = {
val deposit =
val base = Account("Ann", 100)
val balance = base.balance + deposit
val updated = base.copy(balance = balance)
println("owner=" + updated.owner)
println("oldBalance=" + base.balance)
println("newBalance=" + updated.balance)
}
}
case class Account(owner: String, balance: Int)
object Main {
def main(args: Array[String]): Unit = {
val deposit =
val base = Account("Ann", 100)
val balance = base.balance + deposit
val updated = base.copy(balance = balance)
println("owner=" + updated.owner)
println("oldBalance=" + base.balance)
println("newBalance=" + updated.balance)
}
}
copy-update
The generated `copy` method returns a new case class instance with selected fields replaced. The original stays unchanged, which keeps state immutable.