class DefaultListMap[A, B <: List[B]] extends HashMap[A, B] { override def default(key: A) = List[B]() }
I wan't to create map A -> List[B]
. In my case it is Long -> List[String]
but when I get key from map that doesn't have value I would like to create empty List
instead of Exception
being thrown. I tried different combinations but I don't know how to make code above pass the compiler.
Thanks in advance.
Per the Scaladoc, “implements immutable maps using a list-based data structure.” As shown in the examples, elements that are added are prepended to the head of the list. Keys of the map are returned in sorted order. Therefore, all traversal methods (such as foreach) return keys in that order.
Map class explicitly. If you want to use both mutable and immutable Maps in the same, then you can continue to refer to the immutable Map as Map but you can refer to the mutable set as mutable. Map. While defining empty map, the type annotation is necessary as the system needs to assign a concrete type to variable.
=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .
Why not to use withDefaultValue(value)?
scala> val m = Map[Int, List[String]]().withDefaultValue(List()) m: scala.collection.immutable.Map[Int,List[String]] = Map() scala> m(123) res1: List[String] = List()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With