Scala - Mutables and Immutable Collections
In Scala, collections play a fundamental role in managing and processing data efficiently. Scala provides both mutable and immutable collections, offering developers flexibility in choosing the appropriate collection type based on their use case and performance requirements.
Immutable collections in Scala are designed to be thread-safe and cannot be modified after creation. This immutability ensures predictable behavior and simplifies concurrency management in multi-threaded environments. Immutable collections include List, Set, Map, and others, and operations on these collections return new collections without modifying the original.
Mutable vs Immutable:
Values
You can name the results of expressions with the value keyword. Referencing a value doesn’t re-compute it.
Variable
var keyword is use to define a variable. Variables are immutable. Variables are similar to values, except we can re-assign them.
REPL (Read Evaluate Print Loop)
The REPL is a command line interpreter which is use to test our Scala code. It is simple to start a REPL session, just type Scala
on your operating system command line and write a simple equation and the output will be:
When we do not assign the result of our equation to any variable, the REPL automatically creates variable that start with the name res
. The output of variable is stored in res0
; the next one is stored in res1
, and so on.
REPL is also immutable, the reference example can be use as a reference.
Scala - Mutables and Immutable Collections