产量 - foreach - refactor

时间:2018-03-25 16:54:08

标签: scala foreach yield

我是Scala的新手,我有以下代码:

   case _ => {
      val tempA = col2.head
      val collect = col2.drop(1)

      orderCol(collect).foreach {
        tmpCol => (0 until 10).foreach(
          a => (0 until 12).foreach {
            b => {
              val tmpBuild = TmpBuilder.build(tempA, b, a)

              if (isFiltered(tmpBuild, tmpCol)) {
                (tmpBuild :: tmpCol).sortBy(r => (r.tempA, r.B))
              }
            }
          }
        )
      }

//      for {
//        tmpCol <- orderCol(collect)
//        a <- 0 until 10
//        b <- 0 until 12
//        tmpBuild = TmpBuilder.build(tempA, b, a)
//        if (isFiltered(tmpBuild, tmpCol))
//      } yield (tmpBuild :: tmpCol).sortBy(r => (r.tempA, r.B))
    }

注释代码的部分正在工作(编译)。由于我正在学习Scala,我想将注释的代码段重写为未注释的,例如:

      orderCol(collect).foreach {
        tmpCol => (0 until 10).foreach(
          a => (0 until 12).foreach {
            b => {
              val tmpBuild = TmpBuilder.build(tempA, b, a)

              if (isFiltered(tmpBuild, tmpCol)) {
                (tmpBuild :: tmpCol).sortBy(r => (r.tempA, r.B))
              }
            }
          }
        )
      }

但是我收到了以下错误:

Error:(18, 31) type mismatch;
found   : Unit
required: Set[List[test.TmpBuild]]
  orderCol(collect).foreach {

你知道foreach循环有什么问题吗?我应该使用任何地图功能吗? 我将不胜感激任何帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

组合for/yield会产生结果,而foreach会返回单位。请改用flatMap+/map

  orderCol (collect).flatMap {
    tmpCol => (0 until 10).flatMap (
      a => (0 until 12).flatMap {
        b => TmpBuilder.build (tempA, b, a)
      }.filter (tmpBuild => isFiltered (tmpBuild, tmpCol)). map {
         (tmpBuild :: tmpCol).sortBy (r => (r.tempA, r.B))
      }
    )
  }