【发布时间】: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