Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Standard pattern-matching will always match on only exactly one case. You can get close to what you want by using the fact that patterns can be treated as partial functions (see the <a href="http://www.scala-lang.org/docu/files/ScalaReference.pdf" rel="nofollow noreferrer">Language Specification</a>, Section 8.5, <em>Pattern Matching Anonymous Functions</em>) and by defining your own matching operator, though:</p> <pre><code>class MatchAll[S](scrutinee : =&gt;S) { def matchAll[R](patterns : PartialFunction[S,R]*) : Seq[R] = { val evald : S = scrutinee patterns.flatMap(_.lift(evald)) } } implicit def anyToMatchAll[S](scrut : =&gt;S) : MatchAll[S] = new MatchAll[S](scrut) def testAll(x : Int) : Seq[String] = x matchAll ( { case 2 =&gt; "two" }, { case x if x % 2 == 0 =&gt; "even" }, { case x if x % 2 == 1 =&gt; "neither" } ) println(testAll(42).mkString(",")) // prints 'even' println(testAll(2).mkString(",")) // prints 'two,even' println(testAll(1).mkString(",")) // prints 'neither' </code></pre> <p>The syntax is slightly off the usual, but to me such a construction is still a witness to the power of Scala.</p> <p>Your example is now written as:</p> <pre><code>// prints both 'foo' and 'bar' "both" matchAll ( { case "both" | "foo" =&gt; println("foo") }, { case "both" | "bar" =&gt; println("bar") } ) </code></pre> <p>(<strong>Edit</strong> <a href="https://stackoverflow.com/users/257449/huynhjl">huynhjl</a> pointed out that he gave a frighteningly similar answer to <a href="https://stackoverflow.com/questions/6720205/idiomatic-way-to-convert-a-seqb">this question</a>.)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload