遍历列表列表并将元素收集到字符串中

时间:2017-08-23 15:58:44

标签: scala case-class

我有一个嵌套的列表结构,我想遍历列表并打印它的自定义字符串版本

 trait Value{
          def myString:String
        }

  case class Student(value: String) extends Value{
    override def myString: String = s"Student =$value"
  }
  case class Employee(value: Double) extends Value{
    override def myString: String = s"Employee =$value"
  }
  case class Department(value: Int) extends Value{
    override def myString: String = s"Dept =$value"
  }

  case class Grp (elements: List[Value] = Nil) extends Value {
    def add (value: Value): Grp = Grp(this.elements ++ List(value))
    override def myString: String = ""
  }

  val group= Grp()
    .add(Student("abc"))
    .add(Employee(100.20))
    .add( Department(10))
    .add( Grp().add( Student("xyz"))) // nested group`e
    .add( Grp().add( Employee("def")))

我希望获得group的字符串表示。如何遍历group来调用myString方法

更新

输出

Student = abc
Employee = 100.20
Department =10
Student =xyz
Employee= def

1 个答案:

答案 0 :(得分:0)

试试这个

group.elements.map(_.value.myString).mkString("\n")

注意

您的Grp课程继承自Value,因此上述解决方案实际上应该是您的小组myString课程中Grp的价值。然后,要获得Grp的字符串表示,只需调用group.myString

澄清,

case class Grp (elements: List[Value] = Nil) extends Value {
    def add (value: Value): Grp = Grp(this.elements ++ List(value))
    override def myString: String = elements match {
        case e::rest => elements.map(_.myString).mkString("\n")
        case _ => ""
    }
}

现在只需groups.myString来获取字符串