【问题标题】:How to transform Scala collection of Option[X] to collection of X如何将 Option[X] 的 Scala 集合转换为 X 的集合
【发布时间】:2011-06-11 11:28:22
【问题描述】:

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

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

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

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

...到这个:

List[Int] = List(1)

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

【问题讨论】:

    标签: scala scala-collections scala-option


    【解决方案1】:

    出于教育目的,您可能需要一些替代方案:

    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)
    

    使用 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))
    

    【讨论】:

      【解决方案2】:
      val list1 = List(Some(1), None, Some(2))
      val list2 = list1.flatten // will be: List(1,2)
      

      【讨论】:

      • 值得注意的是,它之所以有效,只是因为存在从 Option[A] 到 GenTraversableOnce[A] 的隐式转换
      • @kosii 看起来(至少在 Scala 2.11.6 中)转换是从 Option[A] 到 Iterable[A]
      猜你喜欢
      • 2013-11-14
      • 2010-10-15
      • 1970-01-01
      • 1970-01-01
      • 2012-12-08
      • 2020-05-06
      • 2010-12-26
      • 1970-01-01
      • 2020-03-20
      相关资源
      最近更新 更多