This chapter is from the book
4.2 Accessing Map Values
In Scala, the analogy between functions and maps is particularly close because you use the()notation to look up key values.
scores("Bob")//Like scores.get("Bob") in Java or scores["Bob"] in JavaScript, Python, or C++
If the map doesn’t contain a value for the requested key, an exception is thrown.
To check whether there is a key with the given value, call thecontainsmethod:
if scores.contains("Donald") then scores("Donald") else 0
Since this call combination is so common, there is a shortcut:
scores.getOrElse("Donald", 0)//If the map contains the key "Bob", return the value; otherwise, return 0.
Finally, the callmap.get(key)returns anOptionobject that is eitherSome(value for key)orNone. We discuss theOptionclass in Section 4.7, “The Option Type,” on page 56.