Represnt list to list with a deliminator

时间:2017-09-02 14:25:28

标签: scala case-class

我想编写自定义toString以将列表列表转换为带分隔符的字符串|

trait Msg {   
  def toCustString(): String
}

trait Ele[T] extends Msg {   
    val value: T    
    override def toCustString(): String = s"${value}"        
}

trait Grp extends Msg {    
  val list: Seq[Msg]
  override def toCustString(): String = ""
}


case class TypeA(value: Int) extends Ele[Int]
case class TypeB(value: String) extends Ele[String]
case class TypeC(value: Float) extends Ele[Float]
case class MyGrp(list: Seq[Msg]) extends Grp

object Demo extends App {
  val grp1 = MyGrp(Seq(TypeA(2)))
  val grp2 = MyGrp(Seq(TypeB("ABC"), TypeC(20)))
  val s=MyGrp(Seq(grp1,grp2))
  print(s)
}

最终输出应为2|ABC|20|。请注意结束时的分隔符

任何人都可以建议如何处理上述嵌套结构的解决方案吗?

我试过以下

  override def toCustString(): String = list.map(_.toCustString()).toString

1 个答案:

答案 0 :(得分:1)

您必须先将list中的所有内容转换为CustString,然后再在其上调用mkString()

trait Msg {
  def toCustString: String
}

trait Ele[T] extends Msg {
  val value: T
  override def toCustString: String = value + "|"
}

trait Grp extends Msg {
  val list: Seq[Msg]
  override def toCustString: String =
    list.map(_.toCustString).mkString
}

测试如下。

case class TypeA(value: Int) extends Ele[Int]
case class TypeB(value: String) extends Ele[String]
case class TypeC(value: Float) extends Ele[Float]
case class MyGrp (list:Seq[Msg]) extends Grp

val grp1 = MyGrp(Seq(TypeA(2)))
val grp2 = MyGrp(Seq(TypeB("ABC"), TypeC(20)))
val s=MyGrp(Seq(grp1,grp2))
println(s.toCustString)   // "2|ABC|20.0|"