Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Matching case classes

Tags:

oop

scala

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?

like image 235
divider Avatar asked Oct 19 '11 20:10

divider


People also ask

What is case class and pattern matching Scala?

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.

How is case class used in pattern matching?

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.

What is Scala match case?

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 are Scala case classes?

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.


Video Answer


1 Answers

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

like image 106
Emil Sit Avatar answered Sep 18 '22 08:09

Emil Sit