【问题标题】:Why does Option require explicit toList inside for loops?为什么 Option 在 for 循环中需要显式的 toList?
【发布时间】:2012-12-20 05:58:38
【问题描述】:

使用带有简单选项的 for 循环有效:

scala> for (lst <- Some(List(1,2,3))) yield lst
res68: Option[List[Int]] = Some(List(1, 2, 3))

但循环遍历 Option 的内容不会:

scala> for (lst <- Some(List(1,2,3)); x <- lst) yield x
<console>:8: error: type mismatch;
 found   : List[Int]
 required: Option[?]
              for (lst <- Some(List(1,2,3)); x <- lst) yield x
                                               ^

...除非选项显式转换为列表:

scala> for (lst <- Some(List(1,2,3)).toList; x <- lst) yield x
res66: List[Int] = List(1, 2, 3)

为什么需要显式列表转换?这是惯用的解决方案吗?

【问题讨论】:

    标签: scala scala-option


    【解决方案1】:
    for (lst <- Some(List(1,2,3)); x <- lst) yield x
    

    被翻译成

    Some(List(1,2,3)).flatMap(lst => lst.map(x => x))
    

    Option 上的 flatMap 方法需要一个返回 Option 的函数,但您传递的是一个返回 List 的函数,并且没有从 ListOption 的隐式转换。

    现在,如果您首先将Option 转换为列表,则将调用ListflatMap 方法,该方法需要一个返回List 的函数,这是您传递给它的内容。

    在这种特殊情况下,我认为最惯用的解决方案是

    Some(List(1,2,3)).flatten.toList
    

    【讨论】:

    • 这就是为什么for (lst &lt;- Some(List(1,2,3)) get; x &lt;- Option(lst)) yield x 也可以工作的原因。很有趣。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 2015-08-19
    • 1970-01-01
    • 2011-09-02
    • 2014-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多