Marko Grdinic Marko Grdinic - 4 months ago 61
Scala Question

How to modify the default value for a GenMap in Scala?

The generic GenMap does not have withDefaultValue and I am not sure how to modify the default directly. Is there a way to do this?

Edit: The function I need it for looks like this:

def declassify(dots: GenSeq[Dot], locations: GenSeq[Dot]): GenMap[Dot, GenSeq[Dot]] = {
dots.groupBy {case dot => findFurthest(dot,locations)}


GenMap is a trait that does not define a way to have/use a default value.

If you you instanciate a GenMap yourself, just use HashMap then you will have withDefaultValue.

Or you can use


to get the same behaviour.


def declassify(dots: GenSeq[Any], locations: GenSeq[Any]): HashMap[Any, GenSeq[Any]] = {
    HashMap(dots.groupBy { case dot => "Furtherest" }.toSeq.seq:_*)

You can use this and add the default value inside or outside of the method or the following to add it inside.

def declassify(dots: GenSeq[Any], locations: GenSeq[Any]): Map[Any, GenSeq[Any]] = {
    HashMap.empty[Any, GenSeq[Any]].withDefaultValue(Seq("default")) ++ dots.groupBy { case dot => "Furtherest" }

Scala often crates a HashMap internal. This will avoid create a new HashMap yourself in this case

  def declassify(dots: GenSeq[String], locations: GenSeq[String]): Map[String, GenSeq[String]] = {
    val x = dots.groupBy { case dot => "Furtherest" }
    val z = x match {
      case y: HashMap[String, GenSeq[String]] => y
      case y => HashMap(x.toSeq.seq: _*)

    z withDefaultValue Seq("default")