La correspondance de motif standard correspond toujours à exactement un cas. Vous pouvez obtenir à ce que vous voulez en utilisant le fait que les modèles peuvent être traités comme des fonctions partielles (voir Language Specification, Section 8.5, Pattern Matching fonctions anonymes) et en définissant votre propre opérateur de correspondance, si:
class MatchAll[S](scrutinee : =>S) {
def matchAll[R](patterns : PartialFunction[S,R]*) : Seq[R] = {
val evald : S = scrutinee
patterns.flatMap(_.lift(evald))
}
}
implicit def anyToMatchAll[S](scrut : =>S) : MatchAll[S] = new MatchAll[S](scrut)
def testAll(x : Int) : Seq[String] = x matchAll (
{ case 2 => "two" },
{ case x if x % 2 == 0 => "even" },
{ case x if x % 2 == 1 => "neither" }
)
println(testAll(42).mkString(",")) // prints 'even'
println(testAll(2).mkString(",")) // prints 'two,even'
println(testAll(1).mkString(",")) // prints 'neither'
La syntaxe est légèrement différente de l'habituel, mais pour moi une telle construction est encore un témoin de la puissance de Scala.
Votre exemple est maintenant écrit:
// prints both 'foo' and 'bar'
"both" matchAll (
{ case "both" | "foo" => println("foo") },
{ case "both" | "bar" => println("bar") }
)
(Modifierhuynhjl a fait remarquer qu'il a donné une réponse effroyablement similaire à this question.)
double possible de [Match "fallthrough": l'exécution même morceau de code pour plus d'un cas] (http://stackoverflow.com/questions/2325863/match- fallthrough-execution-same-piece-of-code-for-more-one-case) – nawfal