list - 如何在 Scala 中合并两种类型的 for 推导式?

标签 list scala for-comprehension

我见过在 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/

相关文章:

c# - 如何按对象中的属性对 List<T> 进行排序

java - 从具有日期比较的列表中删除

Python 列表更新自身

scala - 使用 ThisBuild 在多项目 Scala SBT 上进行测试的不同选项

scala - Scala 中的子类型和类型参数

scala - 当对其中一项的检查返回 false 时结束 for-comprehension 循环

python - 比较 2 个列表列表(字符串和数组)

scala - Scala中Pi的蒙特卡洛计算

Clojure For Comprehension 示例

scala - Scala for 推导式中 val 的作用域规则是什么