35

You can write:

str match { case "foo" | "bar" => ... }

At first glance it looks like | could be an extractor object, however:

str match { case |("foo", "bar") => ... }

does not work. (And I can't see how that could be implemented anyway.)

So it is a magic built-in operator?

(I believe I have seen this question on SO before, but it's impossible to search for...)

Jacek Laskowski
  • 72,696
  • 27
  • 242
  • 420
Knut Arne Vedaa
  • 15,372
  • 11
  • 48
  • 59
  • 1
    Here is an [example](http://stackoverflow.com/questions/6384073/catching-multiple-exceptions-at-once-in-scala/6385333#6385333). – agilesteel Jun 26 '11 at 13:26

2 Answers2

43

| is not implemented in the library, it is interpreted by the Scala compiler. It builds a new pattern that is defined as the disjunction between two subpatterns that don't bind any variable (although the newly formed pattern can itself be bound; i.e., you can write stuff like

try { /*...*/ }
catch {
  case e @ (_: IOException | _: IllegalArgumentException) => /*...*/
}

and e gets as type the most specific supertype of the listed alternatives).

Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234
29

Yes the pipe (|) is a built-in for pattern matching (see the scala language reference). The Pattern matching section (section 8) defines in section 8.1.11 what is called Pattern Alternatives. The definition says:

A pattern alternative p1 | ... | pn consists of a number of alternative patterns pi . All alternative patterns are type checked with the expected type of the pattern. They may no bind variables other than wildcards. The alternative pattern matches a value v if at least one its alternatives matches v.

So yes, the pipe is a built-in that is context sensitive to pattern matching.

Blake Mathman
  • 2,699
  • 1
  • 23
  • 20