7

我希望能够引用包含子类型的列表并从该列表中提取元素并隐式转换它们。示例如下:

scala> sealed trait Person { def id: String }
defined trait Person

scala> case class Employee(id: String, name: String) extends Person
defined class Employee

scala> case class Student(id: String, name: String, age: Int) extends Person
defined class Student

scala> val x: List[Person] = List(Employee("1", "Jon"), Student("2", "Jack", 23))
x: List[Person] = List(Employee(1,Jon), Student(2,Jack,23))

scala> x(0).name
<console>:14: error: value name is not a member of Person
              x(0).name
                   ^

我知道,x(0).asInstanceOf[Employee].name但我希望有一种更优雅的类型。提前致谢。

4

2 回答 2

10

最好的方法是使用模式匹配。因为您使用的是密封特征,所以匹配将是详尽的,这很好。

x(0) match { 
  case Employee(id, name) => ...
  case Student(id, name, age) => ...
}
于 2013-02-04T06:23:58.653 回答
8

好吧,如果你想要员工,你总是可以使用collect

val employees = x collect { case employee: Employee => employee }
于 2013-02-04T06:26:11.457 回答