如果值不为null,则添加到列表 [英] Add to list if value is not null

查看:130
本文介绍了如果值不为null,则添加到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有可能返回空值的函数:

  def func(arg:AnyRef ):String = {
...
}

我想将结果添加到列表中,如果它不为空:

  ... 
val l = func(o)
if(l!= null)
list:+ = l
....
$ b

def func(arg :AnyRef):Option [String] = {
...
}



  ... 
func(o).filter(_!= null).map(f => list:+ = f)
...

但看起来太重了。

有没有更好的解决方案?

解决方案

您可以简单地将选项追加到列表中。这是因为 Option 可以被视为 Iterable (对于,其中一个元素 Some ),这要归功于隐式转换 Option.option2Iterable



因此,对于选项变体( func 的第二个版本),只需要:

  list ++ = func(o)

对于其他变体( func 的第一个版本),您可以首先将 func 的返回值转换为使用 Option.apply (会将 null 转换为该值与一些),然后像上面那样做。其中给出:

  list ++ = Option(func(o))


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

这篇关于如果值不为null,则添加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆