make string using productiterator

别说谁变了你拦得住时间么 提交于 2019-12-11 05:57:09

问题


I want to write to String representation of 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

I want to print key value pairs separated by "="

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

回答1:


This will do the trick:

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

This will produce an output like:

2=Student(abc),3=Employee(100.2),4=Department(10),5=Grp(List(Element(2,Student(xyz))))



来源:https://stackoverflow.com/questions/45812470/make-string-using-productiterator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!