我想迭代一个学生列表
EDITED
case class Group(grp:Person*){
val myList=grp.toList
}
trait Person
case class Student(firstName: String, lastName: String) extends Person
case class Emp(empName: String, empLastName: String) extends Person
case class grp(group: List[Group])
grp(List(Group(Student("a","b"),Emp("c","d")),
Group(Student("e","f"),Emp("g","h"))))
我想打印学生和员工的名字和姓氏
任何其他替代方法都可以使用元组。
答案 0 :(得分:0)
grp(List(Group(Student("a","b"),Emp("c","d")),
Group(Student("e","f"),Emp("g","h")))).group.map(a => a.myList.map(b => b match {
case Student(x,y) => println(x+" "+y);
case Emp(x,y) => println(x+" "+y);
}))
答案 1 :(得分:0)
您应该firstName
成员lastName
和Person
成员:
trait Person {
def firstName: String
def lastName: String
}
并且还更改字段名称的Emp
定义以匹配:
case class Emp(firstName: String, lastName: String) extends Person
现在,您可以执行以下操作:
val groups = grp(...)
groups.flatMap(_.myList).foreach { p =>
println(s"${p.firstName} ${p.lastName}")
}