Java Reference
In-Depth Information
Variables
Scala allows you to decide whether a variable is immutable (read-only) when you declare it. An
immutable variable is declared with the keyword
val
. This means it is a variable that cannot be
changed. Listing C-2 illustrates creating an immutable variable, and Figure
C-2
shows what happens
when you try to change it.
Listing C-2. Immutable Variable
val immutableVar : String = "Hello"
immutableVar = "Hi"
Figure C-2.
Error when trying to change val
Listing C-3 illustrates creating a mutable variable, and Figure
C-3
shows it successfully changed.
Listing C-3. Mutable Variable
var mutableVar = "Hello"
mutableVar = "Hi"
Figure C-3.
var changed successfully
When you assign an initial value to a variable, the Scala compiler can infer the type of the variable
based on the value assigned to it. This is called
type inference
, as illustrated in Listing C-4.
Listing C-4. Type Inference
var var1= 10
var var2 = "Hello world"
In Listing C-4, Scala will infer
var1
to be of the
Int
type and
var2
to be of the
String
type variable.
Collections
Scala collections distinguish between mutable and immutable collections. A mutable collection
can be updated or extended in place. This means you can change, add, or remove elements
of a collection as a side effect. Immutable collections, by contrast, never change. You still have