使字符串中使用productiterator(make string using productit

2019-09-27 13:02发布

我想要写入的字符串表示case class Grp

 trait Value

// define these in different files if you want
case class Student(value: String) extends Value
case class Employee(value: Double) extends Value
case class Department(value: Int) extends Value

case class Element(key: String, value: Value)

case class Grp (elements: List[Element] = Nil) extends Value {
  def add (key: String, value: Value): Grp = Grp(this.elements ++ List(Element(key, value)))

}

  val s=  Grp()
      .add("2", Student("abc"))
      .add("3", Employee(100.20))
      .add("4", Department(10))
      .add("5", Grp().add("2", Student("xyz"))) // nested group

我想打印由“=”分隔的键值对

     print(s.productIterator.mkString(""))

Answer 1:

这将这样的伎俩:

s.elements.map(elem => elem.key.toString + "=" + elem.value.toString).mkString(",")

这将产生等相关的输出:

2 =学生(ABC),3 =员工(100.2),4 =部(10),5 = GRP(列表(单元(2,学生(XYZ))))



文章来源: make string using productiterator