Scala:匹配案例类
以下代码声称 Jack 受雇于建筑业,但 Jane 是经济不景气的另一个受害者:
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 作为学生?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我相信这里发生的是
Student
案例类是在Person
内部声明的。因此,toString
中的case Student
将仅匹配属于特定Person
实例的Student
。如果将
案例类 Student
移动到案例类 Worker
并行(然后从其中删除不必要的extends Person("Jake")
object Narrator
...它的存在只是为了让新学生
最终成为特定于Jake的Person$Student
),你会发现简确实是学生物学的。What I believe is happening here is that the
Student
case class is being declared inside ofPerson
. Hence thecase Student
in thetoString
will only matchStudent
s that are part of a particularPerson
instance.If you move the
case class Student
to be parallel to thecase class Worker
(and then remove the unnecessaryextends Person("Jake")
fromobject Narrator
... which is only there so that thenew Student
wound up being aPerson$Student
specific to Jake), you will find Jane does indeed study biology.Emil 是完全正确的,但这里有一个例子可以清楚地说明:
更准确地说,这行:
确实意味着
不幸的是,虽然 Jane 是在 Jake 上实例化的,但在 Jane 的情况下
this
指向 Jane 本人。Emil is entirely correct, but here's an example to make it clear:
To be more precise, this line:
really means
Unfortunately, while Jane was instantiated on Jake,
this
in Jane's case is pointing to Jane herself.