Pattern matching against Scala Map type

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

    Another version which requires you to specify the keys you want to extract and allows you to match on the values is the following:

    class MapIncluding[K](ks: K*) {
      def unapplySeq[V](m: Map[K, V]): Option[Seq[V]] = if (ks.forall(m.contains)) Some(ks.map(m)) else None
    }
    
    val MapIncludingABC = new MapIncluding("a", "b", "c")
    val MapIncludingAAndB = new MapIncluding("a", "b")
    
    Map("a" -> 1, "b" -> 2) match {
      case MapIncludingABC(a, b, c) => println("Should not happen")
      case MapIncludingAAndB(1, b) => println(s"Value of b inside map is $b")
    }
    

提交回复
热议问题