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>