将列表列表展平为scala中的单个元素列表

时间:2017-09-03 03:17:33

标签: scala

我想展平嵌套列表结构

MyGrp(List(MyGrp(List(TypeA(2))), MyGrp(List(TypeB(ABC), TypeC(20.0)))))

List(Type(A),TypeB(ABC),TypeC(20.0))

 trait Msg {

    def toCustString(flag:Boolean): String
  }

  trait Ele[T] extends Msg {

    val value: T

    override def toCustString(flag:Boolean): String = s"${value}"

  }

  trait Grp extends Msg {

    val list: Seq[Msg]

    override def toCustString(flag: Boolean = false): String = {

      val sep = if (flag) "\n" else "!"
      test((builder: StringBuilder, elem: Msg) => builder.append(s"$sep${elem.toCustString(false)}$sep"))

    }

    def test(acc: (StringBuilder, Msg) => StringBuilder): String = {
      list.foldLeft(StringBuilder.newBuilder)(acc).toString()
    }


  }

case class MyMessage(list:Seq[Msg]) extends Grp
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))
}

我尝试过使用

  1. s.list.flatten但它说'错误:(51,10)没有隐含的观点 可从Msg =>获得scala.collection.GenTraversableOnce [B]。
    s.list.flatten'

  2. s.list.map(x=>x.toCustString())但是这会给出一个字符串形式,我想制作一个列表

1 个答案:

答案 0 :(得分:0)

您可以flatMap使用模式匹配,将非Grp包装到单个元素列表中:

val g = MyGrp(List(MyGrp(List(TypeA(2))), MyGrp(List(TypeB("ABC"), TypeC(20.0f)))))

val out = g.list.flatMap {
  case grp: Grp => grp.list
  case msg => List(msg)
}