6
我希望能夠引用一個列表,其中包含子類型並從該列表中提取元素,並將它們隱式轉換。舉例如下:Scala列表和子類型
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
但我希望有一個與類型更優雅的方式。提前致謝。
在這種情況下,你也可以只在'name'字段添加到特質。 – drexin