获取对arity-0 scala函数

时间:2015-08-05 13:32:21

标签: scala types invocation

Scala允许在没有括号的情况下调用没有参数列表的函数:

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

scala> theAnswer
res5: Int = 42

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

2 个答案:

答案 0 :(得分:6)

可以通过以下方式完成:

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

来自the answer to the similar question

  

规则实际上很简单:每当你必须写_   编译器没有明确地期望一个Function对象。

此调用每次都会创建新实例,因为您正在将“转换”方法转换为函数(所谓的“ETA扩展”)。

答案 1 :(得分:3)

简单地:

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

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