获取对 arity-0 scala 函数的引用
Obtain reference to arity-0 scala function
Scala 允许不带括号调用没有参数列表的函数:
scala> def theAnswer() = 42
theAnswer: ()Int
scala> theAnswer
res5: Int = 42
我如何构造一个计算结果为函数 theAnswer
本身而不是 theAnswer
的结果的 Scala 表达式?或者换句话说,我将如何修改表达式 theAnswer
,以便结果的类型为 () => Int
,而不是类型 Int
?
可以通过以下方式完成:
scala> theAnswer _
res0: () => Int = <function0>
来自the answer to the similar question:
The rule is actually simple: you have to write the _ whenever the
compiler is not explicitly expecting a Function object.
此调用每次都会创建新实例,因为您正在 "converting" 方法运行(所谓的 "ETA expansion")。
简单:
scala> val f = () => theAnswer
f: () => Int = <function0>
scala> val g = theAnswer _
g: () => Int = <function0>
Scala 允许不带括号调用没有参数列表的函数:
scala> def theAnswer() = 42
theAnswer: ()Int
scala> theAnswer
res5: Int = 42
我如何构造一个计算结果为函数 theAnswer
本身而不是 theAnswer
的结果的 Scala 表达式?或者换句话说,我将如何修改表达式 theAnswer
,以便结果的类型为 () => Int
,而不是类型 Int
?
可以通过以下方式完成:
scala> theAnswer _
res0: () => Int = <function0>
来自the answer to the similar question:
The rule is actually simple: you have to write the _ whenever the compiler is not explicitly expecting a Function object.
此调用每次都会创建新实例,因为您正在 "converting" 方法运行(所谓的 "ETA expansion")。
简单:
scala> val f = () => theAnswer
f: () => Int = <function0>
scala> val g = theAnswer _
g: () => Int = <function0>