Add to list if value is not null
10,955
You can simply append the option to the list. This is because an Option
can be treated as an Iterable
(empty forNone
, with one single element forSome
) thanks to the implicit conversion Option.option2Iterable
.
So for the option variant (second version of func
) just do:
list ++= func(o)
For the other variant (first version of func
) you can first convert the return value of func
to an Option using Option.apply
(will turn null
to None
or else wrap the value with Some
) and then do like above. Which gives:
list ++= Option(func(o))
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Author by
Admin
Updated on June 27, 2022Comments
-
Admin about 2 years
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?
-
Randall Schulz over 11 yearsYou should be aware that you're relying on a special behavior in the
Option
factory in whichnull
becomesNone
while non-null
values yieldSome(value)
. -
Régis Jean-Gilles over 11 yearsI know that, and I believe that my answer made it clear (citing myself: "using Option.apply (will turn null to Some or else wrap the value with Some)"). In addition, this behaviour is not an accident, it is properly documented in the scaladoc for
Option.apply
-
Régis Jean-Gilles over 11 yearsOops, now I see that I made a typo, I said "will turn null into Some" instead of "will turn null into None", silly me. Is that what confused you? In any case, this is fixed now.