Suppose I have
import scala.collection.immutable.TreeMap
val tree = new TreeMap[String, List[String]]
Now after above declaration, I want to assign key “k1” to List(“foo”, “bar”)
and then how do i get or read back the key “k1” and also read back non-existent key “k2”?
what happens if I try to read non-existent key “k2” ?
The best way to “mutate” the immutable map is by referring to it in a variable (
varas opposed toval):It can be accessed directly using the
applymethod, where scala syntactic sugar kicks in so you can just access using parens:However, I rarely access maps like this because the method will throw a
MatchErroris the key is not present. Usegetinstead, which returns anOption[V]whereVis the value-type:In this case, the value returned for an absent key is
None. What can I do with an optional result? Well, you can make use of methodsmap,flatMap,filter,collectandgetOrElse. Try and avoid pattern-matching on it, or using theOption.getmethod directly!For example:
EDIT: one way of building a Map without declaring it as a
var, and assuming you are doing this by transforming some separate collection, is to do it via a fold. For example:This may not be possible for your use case