我见过在 Scala 中使用不同的方式,从 Option 等包装器或列表或其他集合中获取一些值。如果我必须从 Option
中取出一个 List[Int]
然后对其进行迭代,这可以在一个 for block 中完成吗?
val l: Option[List[Int]] = Some(List(1,2,3,4))
l: Option[List[Int]] = Some(List(1, 2, 3, 4))
for{
li <- l // li taken out from Option wrapper
number <- li // numbers pulled from li
} yield number*2
cmd7.scala:3: type mismatch;
found : List[Int]
required: Option[?]
number <- li
^
如果我理解正确的话,它希望每个条目都是一个Option
。有没有什么方法可以在不使用两个for循环的情况下实现这种效果?
最佳答案
Is there some way to achieve this effect without two for loops?
您可以通过在 Option[List[Int]]
上调用 toList
来实现此目的,将其转换为 List[List[Int]]
for
理解将 flatMap
覆盖:
for {
| o <- l.toList
| num <- o
| } yield num * 2
res8: List[Int] = List(2, 4, 6, 8)
这将为 None
类型生成一个空列表:
scala> val l: Option[List[Int]] = None
scala> for {
| o <- l.toList
| num <- o
| } yield num * 2
res3: List[Int] = List()
如果选项为空,您还可以使用带有空 List[T]
的 Option[T].getOrElse
作为后备:
scala> for {
| o <- l.getOrElse(List())
| } yield o * 2
res13: List[Int] = List(2, 4, 6, 8)
就我个人而言,我喜欢显式的 map
调用:
scala> l.map(_.map(_ * 2))
res7: Option[List[Int]] = Some(List(2, 4, 6, 8))
关于list - 如何在 Scala 中合并两种类型的 for 推导式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38056307/