【问题标题】:Why I can't call flatMap on Option[List]为什么我不能在 Option[List] 上调用 flatMap
【发布时间】:2016-01-23 23:10:12
【问题描述】:
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 相同?

【问题讨论】:

    标签: scala collections


    【解决方案1】:

    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)
    

    【讨论】:

      【解决方案2】:

      那么,您希望 flatMap 的输出是什么?你不能有Option(1,2,3),可以吗?您只能拥有Option 的一件事,因此,您传递给.flatMap 的函数必须返回一个Option,而不仅仅是任何Iterable,这样您就可以保证最多只有一件事在里面。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-09
        • 2013-01-17
        • 1970-01-01
        • 2016-04-16
        • 2018-03-19
        • 2019-03-02
        相关资源
        最近更新 更多