Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Map with default operation in Scala

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.

like image 426
Lukasz Avatar asked Apr 29 '11 09:04

Lukasz


People also ask

How is map implemented in scala?

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.

How do you make a map in scala?

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.

What does => mean in scala?

=> 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 .


1 Answers

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() 
like image 180
Ilya Klyuchnikov Avatar answered Sep 18 '22 19:09

Ilya Klyuchnikov