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/