Say I have a function that checks whether some operation is applicable to an instance of A and, if so, returns an instance of B or None:
def checker[A,B]( a: A ) : Option[B] = ...
Now I want to form a new collection that contains all valid instances of B, dropping the None values. The following code seems to do the job, but there is certainly a better way:
val as = List[A]( a1, a2, a3, ... )
val bs =
as
.map( (a) => checker(a) ) // List[A] => List[Option[B]]
.filter( _.isDefined ) // List[Option[B]] => List[Option[B]]
.map( _.get ) // List[Option[B]] => List[B]
Thanks!
Scala List filter() method with example. The filter() method is utilized to select all elements of the list which satisfies a stated predicate. Return Type: It returns a new list consisting all the elements of the list which satisfies the given predicate.
Scala filter is a method that is used to select the values in an elements or collection by filtering it with a certain condition. The Scala filter method takes up the condition as the parameter which is a Boolean value and returns the result after filtering over that condition.
The Option in Scala is referred to a carrier of single or no element for a stated type. When a method returns a value which can even be null then Option is utilized i.e, the method defined returns an instance of an Option, in place of returning a single object or a null.
This should do it:
val bs = as.flatMap(checker)
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