Imagine I have a Map[String, String]
in Scala.
I want to match against the full set of key–value pairings in the map.
Something like this ought
You could just look up the values in question, stick them in a tuple, and pattern match on that:
val record = Map("amenity" -> "restaurant", "cuisine" -> "chinese", "name" -> "Golden Palace")
(record.get("amenity"), record.get("cuisine")) match {
case (Some("restaurant"), Some("chinese")) => "a Chinese restaurant"
case (Some("restaurant"), Some("italian")) => "an Italian restaurant"
case (Some("restaurant"), _) => "some other restaurant"
case _ => "something else entirely"
}
Or, you could do some nested matches, which might be a bit cleaner:
val record = Map("amenity" -> "restaurant", "cuisine" -> "chinese", "name" -> "Golden Palace")
record.get("amenity") match {
case Some("restaurant") => record.get("cuisine") match {
case Some("chinese") => "a Chinese restaurant"
case Some("italian") => "an Italian restaurant"
case _ => "some other restaurant"
}
case _ => "something else entirely"
}
Note that map.get(key)
returns an Option[ValueType]
(in this case ValueType would be String), so it will return None
rather than throwing an exception if the key doesn't exist in the map.