获取arty -0 scala函数的引用



Scala允许调用没有参数表的函数时不使用括号:

scala> def theAnswer() = 42
theAnswer: ()Int
scala> theAnswer
res5: Int = 42

我如何构建一个scala表达式,计算函数theAnswer本身,而不是theAnswer的结果?或者换句话说,我如何修改表达式theAnswer,使结果是() => Int类型,而不是Int类型?

可以这样做:

scala> theAnswer _
res0: () => Int = <function0>

从类似问题的答案中:

规则实际上很简单:无论何时,您都必须写_编译器没有显式地期望一个Function对象。

这个调用每次都会创建一个新的实例,因为你正在将方法"转换"为函数(也就是所谓的"ETA扩展")。

简体:

scala> val f = () => theAnswer
f: () => Int = <function0>
scala> val g = theAnswer _
g: () => Int = <function0>

最新更新