将 2 个选项合并为 1 个 [英] Combining 2 Options into 1

查看:40
本文介绍了将 2 个选项合并为 1 个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scala 中是否有一个预定义函数 x 组合了 2 个选项,以便

Is there a predefined function x in Scala that combine 2 Options so that

Some(a) x None => Some(a)
None x Some(b) => Some(b)
None x None => None

推荐答案

是的,这就是 orElse 方法.它选择第一个定义的值,或者 None 如果两者都没有定义.

Yes, this is the orElse method. It chooses the first defined value, or None if neither is defined.

scala> Some(1) orElse None
res0: Option[Int] = Some(1)

scala> None orElse Some(1)
res1: Option[Int] = Some(1)

scala> None orElse None
res2: Option[Nothing] = None

scala> Some(1) orElse Some(2)
res3: Option[Int] = Some(1)

这篇关于将 2 个选项合并为 1 个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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