在Scala中,我们有一个by-name-parameters,我们可以在其中编写
def foo[T](f: => T):T = {
f // invokes f
}
// use as:
foo(println("hello"))
我现在想对一组方法进行相同的处理,也就是说,我想将它们用作:
def foo[T](f:Array[ => T]):T = { // does not work
f(0) // invokes f(0) // does not work
}
foo(println("hi"), println("hello")) // does not work
有什么办法可以做我想要的吗?我想出的最好的是:
def foo[T](f:() => T *):T = {
f(0)() // invokes f(0)
}
// use as:
foo(() => println("hi"), () => println("hello"))
或者
def foo[T](f:Array[() => T]):T = {
f(0)() // invokes f(0)
}
// use as:
foo(Array(() => println("hi"), () => println("hello")))
编辑:提议的SIP-24并不是非常有用,正如Seth Tisue在对此答案的评论中指出的那样。
实用程序功能的以下代码是一个有问题的示例trycatch
:
type unitToT[T] = ()=>T
def trycatch[T](list:unitToT[T] *):T = list.size match {
case i if i > 1 =>
try list.head()
catch { case t:Any => trycatch(list.tail: _*) }
case 1 => list(0)()
case _ => throw new Exception("call list must be non-empty")
}
此处trycatch
获取类型的方法列表,()=>T
并依次应用每个元素,直到成功或到达末尾为止。
现在假设我有两种方法:
def getYahooRate(currencyA:String, currencyB:String):Double = ???
和
def getGoogleRate(currencyA:String, currencyB:String):Double = ???
将一个单位转换currencyA
为currencyB
并输出Double
。
我trycatch
用作:
val usdEuroRate = trycatch(() => getYahooRate("USD", "EUR"),
() => getGoogleRate("USD", "EUR"))
我本来希望:
val usdEuroRate = trycatch(getYahooRate("USD", "EUR"),
getGoogleRate("USD", "EUR")) // does not work
在上面的示例中,我getGoogleRate("USD", "EUR")
只想在getYahooRate("USD", "EUR")
引发异常时被调用。这不是SIP-24的预期行为。
从Scala 2.11.7开始,答案是否定的。但是,这里有SIP-24,因此在某些将来的f: => T*
版本中,可能会使用您的版本。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句