14 Pattern Matching

 

After reading this lesson, you’ll be able to:

  • Define a pattern matching statement.
  • 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 statement, particularly useful when having many different condition branches. A pattern matching statement is the equivalent of the switch/case statement of other languages, such as Java, JavaScript, and C++. Pattern matching is more powerful and versatile than a classic switch/case statement, thanks to its powerful syntax and dedicated support for sealed elements and classes. In this lesson, you’ll learn how pattern matching compares to an if-else statement and its base uses. You’ll also discover to define a pattern matching statement 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.

14.1   If-else Statement versus Pattern Matching

 
 

14.2   Sealed Pattern Matching

 
 
 

14.3   Summary

 
 

14.4   Answers to quick checks

 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest