如何实现回退功能列表 [英] How to implement a list of fallback functions

查看:46
本文介绍了如何实现回退功能列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个返回 Option[Int] 的函数列表,我想返回第一个返回 Some(...) 的结果,而不是计算它之后的其余功能.例如:

Let's say I have a list of functions returning Option[Int] and I want to return the result of the first one returning Some(…), and not compute the rest of the functions after it. For example:

val list = List(
  () => { println("a"); None },
  () => { println("b"); Some(1) },
  () => { println("c"); Some(2) },
  () => { println("d"); None }
)

在这种情况下,结果将是 Some(1),它只会打印 ab(因为其余的是未计算).

In this case, the result will be Some(1), and it will print only a and b (since the rest is not computed).

我的解决方案是

list.foldLeft(Option.empty[Int]) { (a, b) => a orElse b() }

问题是否有更优雅/简洁的方法,或者一些图书馆?

The question if there's a more elegant/concise way of doing it, or maybe some library?

推荐答案

list.view.flatMap(_()).headOption

ab 只被调用一次.cd 永远不会被调用甚至迭代.如果没有 Some() 值,则返回 None.

a and b are only called once. c and d are never invoked or even iterated over. Returns None if there are no Some() values.

如果 list 的类型为 LazyList,则不需要 .view.

The .view wouldn't be needed if list was type LazyList.

这篇关于如何实现回退功能列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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