Pattern matching against Scala Map type

后端 未结 6 745
遥遥无期
遥遥无期 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 01:57

    You could use flatMap to pull out the values you are interested in and then match against them:

    List("amenity","cuisine") flatMap ( record get _ ) match {
      case "restaurant"::"chinese"::_ => "a Chinese restaurant"
      case "restaurant"::"italian"::_ => "an Italian restaurant"
      case "restaurant"::_            => "some other restaurant"
      case _                          => "something else entirely"
    }
    

    See #1 on this snippets page.

    You can check whether an arbitrary list of keys have particular values like so:

    if ( ( keys flatMap ( record get _ ) ) == values ) ...
    

    Note that the above works even if keys can be absent from the map, but if the keys share some values you probably want to use map instead of flatMap and be explicit with Some/None in your list of values. E.g. in this case if "amenity" might be absent and the value of "cuisine" might be "restaurant" (silly for this example, but perhaps not in another context), then case "restaurant"::_ would be ambiguous.

    Also, it is worth noting that case "restaurant"::"chinese"::_ is slightly more efficient than case List("restaurant","chinese") because the latter needlessly checks that there are no more elements after those two.

提交回复
热议问题