迭代自定义对象标量列表

时间:2017-08-17 14:10:54

标签: scala case-class

我想迭代一个学生列表

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"))))
  1. 我想打印学生和员工的名字和姓氏

  2. 任何其他替代方法都可以使用元组。

2 个答案:

答案 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成员lastNamePerson成员:

 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}")
 }