Reputation: 14317
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 configMap
of type Map
contains a key with value "runOnGrid"
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] ...
Upvotes: 0
Views: 8322
Reputation: 434
In case configMap
has a type Map[String, String]
(when you read configs from file), you can do:
val runOnGrid : Boolean = args.configMap.get("runOnGrid") match {
case Some("true") => true
case Some("false") => false
case _ => false
}
Upvotes: 0
Reputation: 37852
How about this workaround:
val runOnGrid : Boolean = args.configMap.get("runOnGrid") match {
case Some(true) => true
case _ => false
}
Upvotes: 3
Reputation: 1029
You are getting compile time error because you are mentioning type to case element, remove that and it will work,
So change to,
val runOnGrid : Boolean = args.configMap.get("runOnGrid") match {
case Some(value) => value // <=== Changed
case _ => false
}
Upvotes: 0
Reputation: 14825
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
}
Upvotes: 5