gpt4 book ai didi

oop - Scala:匹配案例类

转载 作者:行者123 更新时间:2023-12-04 07:27:37 24 4
gpt4 key购买 nike

以下代码声称 jack 受雇于建筑业,但简是经济不景气的另一个受害者:

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 识别为学生?

最佳答案

我相信这里发生的是 Student案例类在 Person 内声明.因此 case StudenttoString只会匹配 Student s 是特定 Person 的一部分实例。

如果您移动 case class Student平行于 case class Worker (然后从 extends Person("Jake") 中删除不必要的 object Narrator ......这只是为了让 new Student 最终成为 Jake 特有的 Person$Student),你会发现 Jane 确实研究生物学。

关于oop - Scala:匹配案例类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7827516/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com