Exploring Pattern Matching
Now we will return to pattern matching and learn about extending capabilities behind case classes. As you will remember from the previous chapter, we can use pattern matching against case classes, where fields of a class can be bound to the variables in the scope of an appropriative case clause. Can we do this for our non-case classes and embed our own custom logic for matching?
In this section, we will learn how to write our own pattern matcher and get acquainted with some standard generic classes which are often used with pattern matching.
Now, let's get started with the minimal example.
- First, we write the following code in the IDE:
case class Wrapper(x:Int) w match {case Wrapper(x) => doSomething(x)}
- Under the hood, the compiler compiled this to the next intermediate form:
val container = Wrapper.unapply(w) if (container.isDefined) { val x = container.get doSomething(x) }
- The
unapply
method of the companion object is called, which must return the class...
- The