The following code claims that Jack is employed in construction, but Jane is yet another victim of the rough economy:
abstract class Person(name: String) {
case class Student(name: String, major: String) extends Person(name)
override def toString(): String = this match {
case Student(name, major) => name + " studies " + major
case Worker(name, occupation) => name + " does " + occupation
case _ => name + " is unemployed"
}
}
case class Worker(name: String, job: String) extends Person(name)
object Narrator extends Person("Jake") {
def main(args: Array[String]) {
var friend: Person = new Student("Jane", "biology")
println("My friend " + friend) //outputs "Jane is unemployed"
friend = new Worker("Jack", "construction")
println("My friend " + friend) //outputs "Jack does construction"
}
}
Why does the match fail to recognize Jane as a Student?
Scala's pattern matching statement is most useful for matching on algebraic types expressed via case classes. Scala also allows the definition of patterns independently of case classes, using unapply methods in extractor objects.
Case classes help us use the power of inheritance to perform pattern matching. The case classes extend a common abstract class. The match expression then evaluates a reference of the abstract class against each pattern expressed by each case class.
Advertisements. Pattern matching is the second most widely used feature of Scala, after function values and closures. Scala provides great support for pattern matching, in processing the messages. A pattern match includes a sequence of alternatives, each starting with the keyword case.
What is Scala Case Class? A Scala Case Class is like a regular class, except it is good for modeling immutable data. It also serves useful in pattern matching, such a class has a default apply() method which handles object construction. A scala case class also has all vals, which means they are immutable.
What I believe is happening here is that the Student
case class is being declared inside of Person
. Hence the case Student
in the toString
will only match Student
s that are part of a particular Person
instance.
If you move the case class Student
to be parallel to the case class Worker
(and then remove the unnecessary extends Person("Jake")
from object Narrator
... which is only there so that the new Student
wound up being a Person$Student
specific to Jake), you will find Jane does indeed study biology.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With