Add to list if value is not null

≡放荡痞女 提交于 2019-12-06 17:32:15

问题


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?


回答1:


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))



回答2:


First you should indicate that the function may/may not return a value where the return value is wrapped in Some or None is returned

def func(arg: AnyRef): Option[String] = {
    //  ...
    Some(value) orElse None
}

With a list from func(0) val list = func(0) collect {case Some(x) => x} which takes only values which are defined using collect.



来源:https://stackoverflow.com/questions/14438021/add-to-list-if-value-is-not-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!