Scala Reactive Programming
上QQ阅读APP看书,第一时间看更新

Immutability

Immutable data is data that we can't change once it's created. In Scala, we can mark immutable data using the val keyword:

scala> val data = "Result" 
data: String = Result 
 
scala> data = "New Value" 
<console>:12: error: reassignment to val 
       data = "New Value" 

Not only the Scala ecosystem (API, frameworks, tools, and more), but also most Scala-based applications use immutable data to represent their models.

In Scala, function arguments are val by default. In most Scala-based applications, we use case classes to represent models as they are immutable by design. We will discuss case classes in the next section.

The following are the benefits of immutability:

  • No side effects
  • Easy to reason about and test
  • Thread safety
  • Easy to write concurrent and parallel programs
In Scala, function arguments are val by default.