如何展平案例类中的序列

时间:2019-07-17 16:42:34

标签: scala scala-collections flatten flatmap

在Scala中,对于包含要分解的数组的案例类,是否可以更有效地使用平面地图?

这是一个有效的代码,但看起来不正确:

object stuff {
    def main(args: Array[String]): Unit = {
        case class Stuff(name: String, stuff: Seq[String])
        case class FlatStuff(name: String, stuff: String)

        val someStuff = Array(Stuff("a", Seq("1", "2", "3")), Stuff("b", Seq("4", "5")))

        val stuffs = someStuff.flatMap(item => {
            val flatten = new Array[FlatStuff](item.stuff.length)
            for (i <- 0 until item.stuff.length) {
                flatten(i) = FlatStuff(item.name, item.stuff(i))
            }
            flatten
        })

        stuffs.foreach(stuff => println(stuff))
    }
}

1 个答案:

答案 0 :(得分:5)

也许一个简单的理解力将更具可读性:

val stuffs = for {
  Stuff(name, stuffArray) <- someStuff // for each name & struffArray in someStuff.
  stuff <- stuffArray // for each stuff in stuffArray.
} yield FlatStuff(name, stuff) // Return a new FlatSutff.

正如@ user6337在评论中所解释的,理解只是mapflatMap的糖语法。
因此,以上内容可以重写为:

someStuff.flatMap {
  case Stuff(name, stuffArray) =>
    stuffArray.map {
      stuff => FlatStuff(name, stuff)
    }
}