Immutable Data Patterns
Returning New State
Compute the next state instead of mutating.
Returning New State
NewStateLabel.scala
object Main {
def main(args: Array[String]): Unit = {
val deposit =
val balance = 100
val newBalance = balance + deposit
val state = if (newBalance > balance) "grew" else "same"
println("balance=" + balance)
println("newBalance=" + newBalance)
println("state=" + state)
}
}
object Main {
def main(args: Array[String]): Unit = {
val deposit =
val balance = 100
val newBalance = balance + deposit
val state = if (newBalance > balance) "grew" else "same"
println("balance=" + balance)
println("newBalance=" + newBalance)
println("state=" + state)
}
}
object Main {
def main(args: Array[String]): Unit = {
val deposit =
val balance = 100
val newBalance = balance + deposit
val state = if (newBalance > balance) "grew" else "same"
println("balance=" + balance)
println("newBalance=" + newBalance)
println("state=" + state)
}
}
new-state-label
Rather than mutating a variable, immutable code computes a new value and a label describing the change. The original value stays available for comparison.