14 Pattern matching

After reading this lesson, you’ll be able to

  • Write code that uses pattern matching as an alternative to an if-else construct
  • Pattern match over a closed set of values

After discovering how to express interfaces in Scala using a trait, you’ll see how to use pattern matching. You can use pattern matching as an alternative to an if-else construct, which is particularly useful when having many different condition branches. The Scala pattern matching looks similar to the switch/case statement of other languages, such as Java, JavaScript, and C++. It is often more powerful and versatile than in other languages, thanks to its expressive syntax and dedicated support for sealed elements and classes. In this lesson, you’ll learn ...

Get Get Programming with Scala now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.