Smartly deal with Option[T] in Scala

2019-06-22 14:26发布

I am developing some code using Scala and I am trying to smartly resolve a basic transformation between collections that contains some Option[T].

Let's say that we have the following list

val list: List[(A, Option[B])] = // Initialization stuff

and we want to apply a transformation to list to obtain the following list

val transformed: List[(B, A)]

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

However I feel that I am missing something. Which is the best way to deal with Option[T]s?

1条回答
我想做一个坏孩纸
2楼-- · 2019-06-22 15:11

You can use 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.

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.

查看更多
登录 后发表回答