Comprehensive Matching

Scala’s pattern matching is quite versatile—you can match literals, constants, and arbitrary values with wildcards, tuples, and lists; you can even match based on types and guards. Let’s explore all that, one at a time.

Matching Literals and Constants

Messages passed between actors are normally String literals, numbers, or tuples. If your message is a literal, you don’t have to do much to match it. Simply type the literal you’d like to match, and you’re done. Suppose we need to determine activities for different days of the week. Assume we get the day as a String and we respond with our activity for that day. Here’s an example of how we can pattern-match the days:

PatternMatching/MatchLiterals.scala
 
def​ activity(day: ...

Get Pragmatic 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.