巧妙地处理Scala中的Option [T] [英] Smartly deal with Option[T] in Scala
问题描述
我正在使用Scala开发一些代码,并且试图巧妙地解决包含Option[T]
的集合之间的基本转换.
I am developing some code using Scala and I am trying to smartly resolve a basic transformation between collections that contains some Option[T]
.
假设我们有以下列表
val list: List[(A, Option[B])] = // Initialization stuff
,我们想对list
进行转换以获取以下列表
and we want to apply a transformation to list
to obtain the following list
val transformed: List[(B, A)]
所有评估为Some[B]
的Option[B]
的
.我发现做到这一点的最佳方法是应用以下转换链:
for all Option[B]
s that evaluate to Some[B]
. The best way I found to do this is to apply the following chain of transformations:
val transformed =
list.filter(_.isDefined)
.map { case (a, Some(b)) => (b, a) }
但是我觉得我缺少一些东西.哪个是处理Option[T]
s的最佳方法?
However I feel that I am missing something. Which is the best way to deal with Option[T]
s?
推荐答案
您可以使用collect
:
val transformed = list.collect {
case (a, Some(b)) => (b, a)
}
按照文档中的定义进行收集:
Collect, as defined in the docs:
通过将部分函数应用于此函数在其上定义的列表的所有元素来构建新集合.
Builds a new collection by applying a partial function to all elements of this list on which the function is defined.
意思是,它仅对与部分函数中定义的任何情况匹配的元素产生结果.我喜欢将其视为filter
和map
的组合.
Meaning, it yields a result only for elements which match any of the cases defined in your partial function. I like to think of it as a combined filter
and map
.
这篇关于巧妙地处理Scala中的Option [T]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!