Take a close look at the [T] option in Scala

I am developing some code using Scala, and I am trying to reasonably allow basic conversion between collections containing some Option[T] .

Say we have the following list

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

and we want to apply the conversion to list to get the following list

 val transformed: List[(B, A)] 

for all Option[B] , which are evaluated to Some[B] . The best way I've found for 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 something is missing. What is the best way to handle Option[T] s?

+5
source share
1 answer

You can use collect :

 val transformed = list.collect { case (a, Some(b)) => (b, a) } 

Assemble as defined in the docs:

Creates a new collection by applying a partial function to all elements of this list on which the function is defined.

Value, this only gives results for elements that match any of the cases defined in your partial function. I like to think of it as a combination of filter and map .

+13
source

Source: https://habr.com/ru/post/1242657/


All Articles