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
:
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With