Pattern matching syntax and variable binding

I seem to recall that there is a syntax for pattern matching which allows me to bind several “levels” simultaneously. For example:

obj match {
  case Xyz1(_,y) => ...
  case Xyz2(x,_) => ...

Isn’t there a way to bind the object Xyz1(_,y) at the same time? certainly obj is already bound that that object, but the compiler doesn’t know the type of obj which is different in the two case clauses.

I looked at this page, but I didn’t find it explained. Maybe I’m imagining it, at least there was a syntax in OCaml for this type of matching.

Yes, you use case a @ Xyz1(_ , y) =>


Thanks. Is that somewhere in the documentation page that I missed?

The other piece of syntax is that if I have two patterns with the same consequence there is someway to use the ‘|’ separator, but I have trouble finding that in the documentation as well.

Look here :
Pattern ::= Pattern1 { ‘|’ Pattern1 }

1 Like

Keep in mind, the Tour of Scala that you are pointing to is (intentionally) not comprehensive documentation: it’s an overview of the most common features, intended for initially learned the language, but avoids diving too deeply into the subtler details such as this, that aren’t used every day.

For the more-precise deep dive, you need to either go to the spec or to the book Programming in Scala (preferred by most people), which isn’t quite as official and formal but tends to be treated as the bible of the language. (Disclaimer: I work for the publisher.)

1 Like