以下代码声称杰克受雇于建筑业,但简是另一个粗暴经济的受害者:
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"
}
}
为什么匹配无法将Jane识别为学生?
答案 0 :(得分:5)
我认为这里发生的是Student
案例类是在Person
内声明的。因此,case Student
中的toString
仅匹配属于特定Student
实例的Person
。
如果您将case class Student
移至与case class Worker
平行(然后从extends Person("Jake")
移除不必要的object Narrator
...只有那样new Student
{1}}成为杰克特有的Person$Student
,你会发现简确实在研究生物学。
答案 1 :(得分:4)
scala> case class A(a: String) {
| case class B(b: String)
| def who(obj: Any) = obj match {
| case B(b) => println("I'm A("+a+").B("+b+").")
| case b: A#B => println("I'm B("+b+") from some A")
| case other => println("Who am I?")
| }
| }
defined class A
scala> val a1 = A("a1")
a1: A = A(a1)
scala> val a2 = A("a2")
a2: A = A(a2)
scala> val b1= a1.B("b1")
b1: a1.B = B(b1)
scala> val b2 = a2.B("b2")
b2: a2.B = B(b2)
scala> a1 who b1
I'm A(a1).B(b1).
scala> a1 who b2
I'm B(B(b2)) from some A
更确切地说,这一行:
case Student(name, major) => name + " studies " + major
真的意味着
case this.Student(name, major) => name + " studies " + major
不幸的是,虽然Jane在Jake身上实例化,但Jane的案例中this
指向Jane本人。