scala 如何从列表[选项]中过滤无?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10104558/
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 04:05:26  来源:igfitidea点击:

How to filter None's out of List[Option]?

scalaoption

提问by Ralph

If I have a List[Option[A]]in Scala, what is the idiomatic way to filter out the Nonevalues?

如果我List[Option[A]]在 Scala 中有一个,那么过滤掉None值的惯用方法是什么?

One way is to use the following:

一种方法是使用以下方法:

val someList: List[Option[String]] = List(Some("Hello"), None, Some("Goodbye"))
someList.filter(_ != None)

Is there a more "idiomatic" way? This does seem pretty simple.

有没有更“惯用”的方式?这看起来很简单。

回答by Nicolas

If you want to get rid of the options at the same time, you can use flatten:

如果你想同时摆脱这些选项,你可以使用flatten

scala> someList.flatten
res0: List[String] = List(Hello, Goodbye)

回答by Kevin O'Riordan

someList.filter(_.isDefined)if you want to keep the result type as List[Option[A]]

someList.filter(_.isDefined)如果你想保持结果类型为 List[Option[A]]

回答by dcastro

The catslibrary also has flattenOption, which turns any F[Option[A]]into an F[A](where F[_]is a FunctorFilter)

cats文库还具有flattenOption,这将任何F[Option[A]]进入的F[A](其中,F[_]FunctorFilter

import cats.implicits._

List(Some(1), Some(2), None).flattenOption == List(1, 2)