Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smartly deal with Option[T] in Scala

Tags:

scala

optional

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?

like image 962
riccardo.cardin Avatar asked Feb 09 '16 21:02

riccardo.cardin


1 Answers

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.

like image 198
Zoltán Avatar answered Sep 29 '22 06:09

Zoltán