如何编写"orElse"的惰性,可变参数版本. [英] How to write a lazy, variable argument version of "orElse"

查看:63
本文介绍了如何编写"orElse"的惰性,可变参数版本.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从Option编写一个通用的orElse方法,该方法采用可变数量的参数?也就是说,代替:

Is it possible to write a generalised orElse method from Option that takes a variable number of arguments? That is, instead of:

lazy val o1 = { println("foo"); None }
lazy val o2 = { println("bar"); Some("bar") }
lazy val o3 = { println("baz"); Some("baz") } 
// ...
o1 orElse o2 orElse o3 // orElse ...

您可以使用:

orElse(o1, o2, o3) //, ...

推荐答案

根据

According to the The Scala Language Specification (4.6 Function Declarations and Definitions) you cannot define varargs by-name parameters:

ParamType ::= Type
| ‘=>’ Type
| Type ‘*’

scala> def orElse(x : (=> String)*)
<console>:1: error: no by-name parameter type allowed here
       def orElse(x : (=> String)*)

您可以将lazy arg替换为function和隐式类型转换:

You could replace the lazy arg with function and an implicit type conversion:

def orElse[T](x : (()=> Option[T])*) : Option[T] = 
    if(x.isEmpty) None else x.first.apply.orElse(orElse((x drop 1) :_*))
implicit def anyToFun0[T](t : => T) : (() => T) = () => t
orElse(o1, o2, o3)

这篇关于如何编写"orElse"的惰性,可变参数版本.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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