如何将 Option[X] 的 Scala 集合转换为 X 的集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4730842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 02:44:25  来源:igfitidea点击:

How to transform Scala collection of Option[X] to collection of X

scalascala-collectionsscala-option

提问by npad

I'm starting to explore Scala, and one of the things I'm intrigued by is the Optiontype and the promise of being able to eliminate nullrelated errors.

我开始探索 Scala,我感兴趣的一件事是它的Option类型和能够消除null相关错误的承诺。

However I haven't been able to work out how to transform a list (or other collection) of, say, Option[String], to a collection of String(obviously filtering out any values that are None).

但是,我无法弄清楚如何将 的列表(或其他集合)转换Option[String]为 的集合String(显然过滤掉了 的任何值None)。

In other words, how do I get from this:

换句话说,我如何从中获得:

List[Option[Int]] = List(Some(1))

... to this:

...到这个:

List[Int] = List(1)

I'm using Scala 2.8 if that has any impact on the answer.

如果这对答案有任何影响,我将使用 Scala 2.8。

回答by Madoc

val list1 = List(Some(1), None, Some(2))
val list2 = list1.flatten // will be: List(1,2)

回答by retronym

For educational purposes, you might like some alternatives:

出于教育目的,您可能会喜欢一些替代方案:

scala> val list1 = List(Some(1), None, Some(2))
list1: List[Option[Int]] = List(Some(1), None, Some(2))

scala> list1 flatten
res0: List[Int] = List(1, 2)

// Expanded to show the implicit parameter
scala> list1.flatten(Option.option2Iterable)
res1: List[Int] = List(1, 2)

scala> list1 flatMap (x => x)
res2: List[Int] = List(1, 2)

scala> list1 flatMap Option.option2Iterable
res3: List[Int] = List(1, 2)

// collect is a simultaneous map + filter
scala> list1 collect { case Some(x) => x }
res4: List[Int] = List(1, 2)

With Scalaz, you can perform a slightly different operation called sequence, that returns Option[List[Int]].

使用 Scalaz,您可以执行一个稍微不同的操作,称为sequence,返回Option[List[Int]]

scala> import scalaz._; import Scalaz._
import scalaz._
import Scalaz._

scala> val list1: List[Option[Int]] = List(Some(1), None, Some(2)) 
list1: List[Option[Int]] = List(Some(1), None, Some(2))

scala> list1.sequence                                              
res1: Option[List[Int]] = None

scala> val list2: List[Option[Int]] = List(Some(1), Some(2))         
list2: List[Option[Int]] = List(Some(1), Some(2))

scala> list2.sequence
res2: Option[List[Int]] = Some(List(1, 2))