如何将 Option[X] 的 Scala 集合转换为 X 的集合 [英] How to transform Scala collection of Option[X] to collection of X

查看:40
本文介绍了如何将 Option[X] 的 Scala 集合转换为 X 的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm starting to explore Scala, and one of the things I'm intrigued by is the Option type and the promise of being able to eliminate null related errors.

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

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).

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

In other words, how do I get from this:

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

...到这个:

List[Int] = List(1)

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

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

推荐答案

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

这篇关于如何将 Option[X] 的 Scala 集合转换为 X 的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆