O'Reilly logo

Pragmatic Scala by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required