Giovanni Azua Giovanni Azua - 10 months ago 47
Scala Question

How to unwrap an Option with its correct type in pattern matching?

I have the following code that illustrates what I'd like to achieve but it doesn't compile ... I'd like to find out whether the

of type
contains a key with value
and if it does get its Boolean value.

val runOnGrid : Boolean = args.configMap.get("runOnGrid") match {
case Some(value) : Option[Boolean] => value // <=== compiler error
case None => false

but this doesn't work because I can't do
Some(value) : Option[Boolean]
namely I'm constrained to choose between matching by the value or by the type. To achieve this apparently I need better Scala kung fu ... can anyone advice?

UPDATE: meantime I figured this horrendous way to do it

val runOnGrid = args.configMap.get(("runOnGrid") match {
case Some(value) => value.isInstanceOf[Boolean] && value.asInstanceOf[Boolean]
case _ => false

UPDATE: ConfigMap is defined inside Scalatest as:

class ConfigMap(underlying: Map[String, Any]) extends Map[String, Any] ...


You can do something like this Some(value: Boolean) value inside Some can be given a type annotation

val runOnGrid : Boolean = args.configMap.get("runOnGrid") match {
    case Some(value: Boolean) => value
    case _ => false