假设我有以下内容:
trait Person {
val name: String
}
case class Student(val name: String) extends Person
case class Teacher(val name: String, students: List[Student]) extends Person
我想要一个函数函数,它可以采用任何Person
实现,匹配特定类型,然后返回可能的最特定类型。(我知道这可能不是最聪明的事情,但请耐心等待。)让我们这样说:
def teacherGreeting(teacher: Teacher): (Teacher, String) = {
val names = teacher.students.map(_.name).mkString(", ")
(teacher, s"Hello ${teacher.name}, your students are $names")
}
def greet[P <: Person](person: P): (P, String) = person match {
case Student(name) => (person, s"Hello $name")
case Teacher(name, students) => teacherGreeting(person)
}
但后来我得到:
<console>:19: error: type mismatch;
found : P
required: Teacher
case Teacher(name, students) => teacherGreeting(person)
^
如果我有teacherGreeting
inside of的逻辑greet
,我没有任何问题。那么,为什么编译器不知道P
在这个代码分支中必须是 a Teacher
?
如果我使用匹配的值:
def greet[P <: Person](person: P): (P, String) = person match {
case Student(name) => (person, s"Hello $name")
case teacher @ Teacher(name, students) => teacherGreeting(teacher)
}
错误只是稍后发生,结果为teacherGreeting
, 而不是输入:
error: type mismatch;
found : (Teacher, String)
required: (P, String)
case teacher @ Teacher(name, students) => teacherGreeting(teacher)
^
有没有办法避免铸造?