Pattern matching against Scala Map type

后端 未结 6 734
遥遥无期
遥遥无期 2020-12-31 01:15

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

6条回答
  •  长发绾君心
    2020-12-31 02:12

    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.

提交回复
热议问题