【问题标题】:flatMap strange behaviour on List of List of Integers整数列表列表上的 flatMap 奇怪行为
【发布时间】:2015-09-11 18:36:24
【问题描述】:

在 Scala 中:

scala> val xs = List(List(1, 3, 5), List(3, 4, 30))
xs: List[List[Int]] = List(List(1, 3, 5), List(3, 4, 30))

scala> xs flatMap {x => x + 1}
<console>:9: error: type mismatch;
 found   : Int(1)
 required: String
              xs flatMap {x => x + 1}

为什么?

【问题讨论】:

    标签: scala flatmap


    【解决方案1】:

    最简单的解决方案是在执行 map 之前展平你的列表:

    xs.flatten.map { _ + 1 }
    

    您的错误的原因是 flatMap 不会展平您执行它的集合,它会展平函数在其参数中返回的结果。

    【讨论】:

      【解决方案2】:

      该错误消息中的String 是一个不幸的误导性推论。

      理想情况下编译器会给你的错误是

      found   : Int => Int
      required: Int => List[Int]
      

      【讨论】:

      • 我接受你的回答,因为这就是我要问的问题
      【解决方案3】:

      flatMap 中的xList[Int] 而不是Int,我想到了两个解决方案:

      scala> xs.flatMap(identity).map(_ + 1)
      res2: List[Int] = List(2, 4, 6, 4, 5, 31)
      
      scala> xs.flatMap(_.map(_ + 1))
      res3: List[Int] = List(2, 4, 6, 4, 5, 31)
      

      【讨论】:

      • 您可以使用flatten 代替flatMap(identity)。 for 表达式在这里也很合适。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多