Coalescing options in Scala

半腔热情 提交于 2019-12-01 03:39:09

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

How about:

values.flatten.headOption

This works since Option is implicitly convertible to Iterable, so flatten works much in the same way as a list of lists.

Auto answer:

The native mechanism (without implementing a coalesce function) is the chaining of calls to orElse method:

> None.orElse(Some(3)).orElse(Some(4))
res0: Option[Int] = Some(3)

> Some(1).orElse(None).orElse(Some(3)).orElse(Some(4))
res1: Option[Int] = Some(1)

> None.orElse(None)
res2: Option[Nothing] = None

Find first defined option:

def coalesce[T](values: Option[T]*): Option[T] =
  values.find(_.isDefined).flatten
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!