I have the function that could return null value:
def func(arg: AnyRef): String = {
...
}
and I want to add the result to list, if it is not null:
...
val l = func(o)
if (l != null)
list :+= l
....
or
def func(arg: AnyRef): Option[String] = {
...
}
...
func(o).filter(_ != null).map(f => list :+= f)
...
But it looks too heavy.
Are there any better solutions?
You can simply append the option to the list. This is because an
Optioncan be treated as anIterable(empty forNone, with one single element forSome) thanks to the implicit conversionOption.option2Iterable.So for the option variant (second version of
func) just do:For the other variant (first version of
func) you can first convert the return value offuncto an Option usingOption.apply(will turnnulltoNoneor else wrap the value withSome) and then do like above. Which gives: