Scala 中的合并选项 [英] Coalescing options in Scala

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

问题描述

大多数 SQL 实现(这个问题与 SQL 无关,它只是一个例子)提供函数 COALESCE(x1,x2,...,xn) 返回 x1 如果不是 NULL, x2 否则只有 x2 不是 NULL ,以此类推.如果所有 xi 值都是 NULL,则结果为 NULL.

Most SQL implementations (this question has nothing to do with SQL, it is just an example) offer the function COALESCE(x1,x2,...,xn) which returns x1 if it is not NULL, x2 otherwise only if x2 is not NULL neither and so on. If all xi values are NULL then the result is NULL.

我想在 Scala 中得到类似于 SQL 的 COALESCE 的东西,用于 Option 值被 NULL 替换为 None.我给你举几个例子:

I wanted to get something like SQL's COALESCE in Scala for Option values being NULL replaced by None. I'll give you some examples:

> coalesce(None,Some(3),Some(4))
res0: Some(3)

> coalesce(Some(1),None,Some(3),Some(4))
res1: Some(1)

> coalesce(None,None)
res2: None

所以我将其实现为:

def coalesce[T](values: Option[T]*): Option[T] = 
    (List[T]() /: values)((prev: List[T], cur: Option[T]) =>
                          prev:::cur.toList).headOption

它工作正常,但我想知道是否已经存在这样的功能作为 Scala 的一部分实现.

It works fine but I wonder if already exists something like this function implemented as part of Scala.

推荐答案

简而言之,您可以使用 collectFirst.这将一步完成,最多遍历一次集合.

Shorter still, you could use collectFirst. This will do it in one step, with at most one traversal of the collection.

def coalesce[A](values: Option[A]*): Option[A] =
    values collectFirst { case Some(a) => a }


scala> coalesce(Some(1),None,Some(3),Some(4))
res15: Option[Int] = Some(1)

scala> coalesce(None,None)
res16: Option[Nothing] = None

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

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