Pattern matching against Scala Map type

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

    I find the following solution using extractors the most similar to case classes. It's mostly syntactic gravy though.

    object Ex {
       def unapply(m: Map[String, Int]) : Option[(Int,Int) = for {
           a <- m.get("A")
           b <- m.get("B")
       } yield (a, b)
    }
    
    val ms = List(Map("A" -> 1, "B" -> 2),
        Map("C" -> 1),
        Map("C" -> 1, "A" -> 2, "B" -> 3),
        Map("C" -> 1, "A" -> 1, "B" -> 2)
        )  
    
    ms.map {
        case Ex(1, 2) => println("match")
        case _        => println("nomatch")
    }
    

提交回复
热议问题