Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala List and Subtypes

I want to be able to refer to a list that contains subtypes and pull elements from that list and have them implicitly casted. Example follows:

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
                   ^

I know that x(0).asInstanceOf[Employee].name but I was hoping there was a more elegant way with types. Thanks in advance.

like image 364
user2038626 Avatar asked Feb 04 '13 06:02

user2038626


2 Answers

The best way is to use pattern matching. Because you are using a sealed trait the match will be exhaustive which is nice.

x(0) match { 
  case Employee(id, name) => ...
  case Student(id, name, age) => ...
}
like image 168
Ivan Meredith Avatar answered Nov 04 '22 20:11

Ivan Meredith


Well, if you want the employees, you could always use a collect:

val employees = x collect { case employee: Employee => employee }
like image 20
Daniel C. Sobral Avatar answered Nov 04 '22 19:11

Daniel C. Sobral