Attempted removal of nonexistent elements from a map is handled gracefully:
Map values can be iterated:
If a nonexistent map key is requested using myMap(missingKey)
, a NoSuchElementException
will be thrown.
If a nonexistent map key is requested using myMap(missingKey)
, a NoSuchElementException
will be thrown.
Default values may be provided using either getOrElse
or withDefaultValue
for the entire map:
Maps do not contain multiple identical pairs:
Maps insertion with duplicate key updates previous entry with subsequent value:
Maps can be added to easily:
Map elements can be removed easily:
A Map
is an Iterable
consisting of pairs of keys and values (also named mappings or associations).
A Map
is an Iterable
consisting of pairs of keys and values (also named mappings or associations). Scala's Predef class offers an implicit conversion that lets you write key -> value
as an alternate syntax for the pair (key, value)
. For instance Map("x" -> 24, "y" -> 25, "z" -> 26)
means exactly the same as Map(("x", 24), ("y", 25), ("z", 26))
, but reads better.
The fundamental operations on maps are similar to those on sets. They are summarized in the following table and fall into the following categories:
apply
, get
, getOrElse
, contains
, and isDefinedAt
. These turn maps into partial functions from keys to values. The fundamental lookup method for a map is: def get(key): Option[Value]
. The operation "m get key
" tests whether the map contains an association for the given key. If so, it returns the associated value in a Some
. If no key is defined in the map, get returns None
. Maps also define an apply
method that returns the value associated with a given key directly, without wrapping it in an Option
. If the key is not defined in the map, an exception is raised.+
, ++
, updated
, which let you add new bindings to a map or change existing bindings.-
, --
, which remove bindings from a map.keys
, keySet
, keysIterator
, values
, valuesIterator
, which return a map's keys and values separately in various forms.filterKeys
and mapValues
, which produce a new map by filtering and transforming bindings of an existing map.Maps can be created easily:
Maps may be accessed:
Map keys may be of mixed type:
Map equivalency is independent of order:
Map elements can be removed in multiple:
Map elements can be removed with a tuple:
The parameterless execute method has been deprecated and will be removed in a future version of ScalaTest. Please invoke execute with empty parens instead: execute().
The trap method is no longer needed for demos in the REPL, which now abreviates stack traces, and will be removed in a future version of ScalaTest