You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
As discussed in the previous lesson, this works because a method named `apply` is generated inside `Person`’s companion object.
66
-
67
-
68
-
69
68
## An `unapply` method
70
69
71
-
In the previous lesson on companion objects you saw how to write `unapply` methods. A great thing about case classes is that they automatically generate an `unapply` method, so you don’t have to write one.
70
+
In the previous lesson on companion objects you saw how to write `unapply` methods. A great thing about a case class is that it automatically generates an `unapply` method for your class, so you don’t have to write one.
72
71
73
72
To demonstrate this, imagine that you have this trait:
74
73
@@ -85,7 +84,7 @@ case class Student(name: String, year: Int) extends Person
Because those are defined as case classes — and a case class has a built-in `unapply`method — you can write a match expression like this:
87
+
Because those are defined as case classes — and they have built-in `unapply`methods — you can write a match expression like this:
89
88
90
89
```scala
91
90
defgetPrintableString(p: Person):String= p match {
@@ -187,11 +186,3 @@ res0: Person = Person(Christina,niece)
187
186
While all of these features are great benefits to functional programming, as they write in the book, [Programming in Scala](https://www.amazon.com/Programming-Scala-Updated-2-12/dp/0981531687/) (Odersky, Spoon, and Venners), “the biggest advantage of case classes is that they support pattern matching.” Pattern matching is a major feature of FP languages, and Scala’s case classes provide a simple way to implement pattern matching in match expressions and other areas.
0 commit comments