Java Reference
In-Depth Information
Several things are new with this line of code. First, it's pretty awesome that you can create a Map
and associate a key to a value directly, using the syntax ->. There's no need to add elements
manually like in Java:
Map<String, Integer> authorsToAge = new HashMap<>();
authorsToAge.put("Raoul", 23);
authorsToAge.put("Mario", 40);
authorsToAge.put("Alan", 53);
There are discussions to add similar syntactic sugar in future versions of Java, but it's not
the variable authorsToAge. You could have explicitly written val authors-ToAge : Map[String,
Int], but Scala can infer the type of the variable for you. (Note that the code is still statically
checked! All variables have a given type at compile time.) We'll come back to this feature later in
the chapter. Third, you use the val keyword instead of var. What's the difference? The keyword
val means that the variable is read-only and can't be reassigned to (just like final in Java). The
var keyword means the variable is read-write.
What about other collections? You can create a List (a singly linked list) or a Set (no duplicates)
as easily:
val authors = List("Raoul", "Mario", "Alan")
val numbers = Set(1, 1, 2, 3, 5, 8)
The authors variable will have three elements and the numbers variable will have five elements.
Immutable vs. mutable
One important property to keep in mind is that the collections created previously are
immutable
by default. This means they can't be changed after they're created. This is useful because you
know that accessing the collection at any point in your program will always yield a collection
with the same elements.
So how can you update an immutable collection in Scala? To come back to the terminology used
in the previous chapter, such collections in Scala are said to be
persistent
: updating a collection
produces a new collection that shares as much as possible with its previous version, which
persists without being affected by changes like we showed in
figures 14.3
and
14.4
.
As a
consequence of this property, your code will have fewer
implicit data dependences
: there's less
Search WWH ::
Custom Search