Chapter 4. Pattern Matching
Scala’s pattern matching provides deep inspection and decomposition of objects in a variety of ways. It’s one of my favorite features in Scala. For your own types, you can follow a protocol that allows you to control the visibility of internal state and how to expose it to users. The terms extraction and destructuring are sometimes used for this capability.
Pattern matching can be used in several code contexts, as we’ve already seen in “A Sample Application” and “Partial Functions”. We’ll start with a change in Scala 3 for better type safety, followed by a quick tour of common and straightforward usage examples, then explore more advanced scenarios. We’ll cover a few more pattern-matching features in later chapters, once we have the background to understand them.
Safer Pattern Matching with Matchable
Let’s begin with an important change in Scala 3’s type system that is designed to make compile-time checking of pattern-matching expressions more robust.
Scala 3 introduced an immutable wrapper around Arrays called scala.IArray. Arrays in Java are mutable, so this is intended as a safer way to work with them. In fact, IArray is a type alias for Array to avoid the overhead of wrapping arrays, which means that pattern matching introduces a hole in the abstraction. Using the Scala 3.0 REPL without the -source:future setting, observe the following:
// src/script/scala/progscala3/patternmatching/Matchable.scalascala>valiarray=IArray(1,2,3,4,5)|iarray ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access