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?
You can use
collect
:Collect, as defined in the docs:
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
andmap
.