scala - 为什么我不能在 Option[List] 上调用 flatMap

标签 scala collections

println(List(List(1,2,3)).flatMap(identity))

= 列表(1,2,3)

println(Iterable(List(1,2,3)).flatMap(identity))

同样的结果

println(Option(List(1,2,3)).flatMap(identity))

    Error:(8, 39) type mismatch;
 found   : List[Int] => List[Int]
 required: List[Int] => Option[?]
  println(Option(List(1,2,3)).flatMap(identity))
                                      ^
                                                  ^

我认为存在 option2iterable 隐式转换,所以 Options 的行为应该与 Iterable 相同?

最佳答案

Option 伴侣中有一个隐式定义:

/** An implicit conversion that converts an option to an iterable value
 */
implicit def option2Iterable[A](xo: Option[A]): Iterable[A] = xo.toList

但它不适用于这种情况,因为Option有自己的flatMap方法。

def flatMap[B](f: A => Option[B]): Option[B]

您可以将 Option 强制为 Iterable 以强制应用隐式:

scala> (Option(List(1, 2, 3)): Iterable[List[Int]]).flatMap(identity)
res0: Iterable[Int] = List(1, 2, 3)

或者直接调用.toIterable:

scala> Option(List(1, 2, 3)).toIterable.flatMap(identity)
res1: Iterable[Int] = List(1, 2, 3)

关于scala - 为什么我不能在 Option[List] 上调用 flatMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34970080/

相关文章:

scala - 将多个 scalapb 源目录添加到多项目 SBT 构建

scala - 使用 Scala 的 Actor 时如何避免竞争条件

java - 重启elasticsearch节点

c# - N2 内容管理系统 : Are nested collections of ContentItems possible?

c# - Scala collection 的seq/par/view/force 是否可以被视为违反统一返回类型原则?

java - 如何将 JDK 中的类链接到 scaladoc 生成的文档中?

java - 在 Scala 中使用 Java 泛型类会引发错误数量的类型参数错误

Java集合插入: Set vs.列表

java - 通过特定对象属性在 HashSet/ArrayList 中查找最大值

c++ - 从自定义集合中读取数据(结构数组)