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))
Share:
10,955
Admin
Author by

Admin

Updated on June 27, 2022

Comments

  • Admin
    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
    Randall Schulz over 11 years
    You should be aware that you're relying on a special behavior in the Option factory in which null becomes None while non-null values yield Some(value).
  • Régis Jean-Gilles
    Régis Jean-Gilles over 11 years
    I 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
    Régis Jean-Gilles over 11 years
    Oops, 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.