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, 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 how pattern matching compares to an if-else construct and its base uses. You’ll also discover how to define pattern matching over a sealed set of values and how the compiler can warn you if you forget to consider any of them. Pattern matching also has dedicated support for classes, but you’ll see how this works later in the book when learning about case classes. In the capstone, you’ll use pattern matching to map country names to their timezones.