Mikaël Mayer Mikaël Mayer -4 years ago 168
Scala Question

How to get Map default value if it exist

I would like to retrieve the default value of a Map, if it exists. Here is what I have tried:

def defaultValue[A, B](m: Map[A, B]): Option[B] = {
m match {
case m: Map.WithDefault[A, B] => Some(m.default(null))
case _ => None
}
}


This does not work because
null
is not a subtype of
A
. How to retrieve the default value of a
Map.WithDefault
which has a constant function?

What I have tried

Produce a random value of type
A
? Default values are encoded using constant functions, that's why it needs an argument, but in my case it should not happen that the argument is used. Furthermore, when I put something like
???
of type
Nothing
, it evaluates the argument before trying to return the constant value and thus throws an exception.

My problem is related to this question but they do not provide a way to retrieve the default value directly.

Answer Source

You can add a lower bound, rewriting your method signature as:

def defaultValue[A >: Null <: AnyRef, B](m: Map[A, B]): Option[B]

Or alternatively you can cast null to A with null.asInstanceOf[A]:

case m: Map.WithDefault[A, B] => Some(m.default(null.asInstanceOf[A]))

Not that this version works also for A <: AnyVal (remember that e.g. null.asInstanceOf[Int] == 0).


Just one additional note: you can match against case _: Map.WithDefault[_, _] cause the outer reference in this type test cannot be checked at run time.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download