Alex Rivera | Logout

Explain this pattern matching code

Asked 2010-10-24T12:51:56.837
19

This code is from Querying a Dataset with Scala's Pattern Matching:

object & { def unapply[A](a: A) = Some((a, a)) }

"Julie" match {
  case Brothers(_) & Sisters(_) => "Julie has both brother(s) and sister(s)"
  case Siblings(_) => "Julie's siblings are all the same sex"
  case _ => "Julie has no siblings"
}

// => "Julie has both brother(s) and sister(s)"

How does & actually work? I don't see a Boolean test anywhere for the conjunction. How does this Scala magic work?

Edit
Report

1 Answer

1

For additional info, I recommend reading the Infix Operation Patterns section (8.1.10) of the Scala Language Specification.

An infix operation pattern p op q is a shorthand for the constructor or extractor pattern op(p,q). The precedence and associativity of operators in patterns is the same as in expressions.

Which is pretty much all there is to it, but then you can read about constructor and extractor patterns and patterns in general. It helps separate the syntactic sugar aspect (the "magic" part of it) from the fairly simple idea of pattern matching:

A pattern is built from constants, constructors, variables and type tests. Pattern matching tests whether a given value (or sequence of values) has the shape defined by a pattern, and, if it does, binds the variables in the pattern to the corresponding components of the value (or sequence of values).

answered 2010-10-24T15:09:14.023

Your Answer