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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.