函数f中的参数apply是 a Funcion1,它接受一个按名称调用的类型参数A并返回 a B。因此,f(x)不会评估 call-by-name 参数x,而是将其引用直接传递给f.
res理解如下是有帮助的:
def res[C]: Int = apply[C, Int](const, ???)
在您的示例C中将是一个非特定类型。现在const在这一行中推断出的类型参数是什么?它是=> C。不幸的是,您不能输入该参数:
def res[C]: Int = apply[C, Int](const[=> C], ???) // illegal syntax
但是您可以验证发生了什么:
def res[C]: Int = apply[C, Int](const[Nothing], ???)
给你
<console>:10: error: type mismatch;
found : Nothing => Int
required: => C => Int
def res[C]: Int = apply[C, Int](const[Nothing], ???)
^
这种类型在内部显示const为 a Function0[Int](因此 Scala 隐含地将按名称调用或“thunk”参数视为没有参数的函数)。您可以再次验证这一点:
def const[A](ignored: A): Int = if (ignored.isInstanceOf[Function0[_]]) 1 else 0
现在Test.res会给你1(意思ignored是确实是一个Function0)。
因此,以不同的方式回答这个问题,const有一个急切的 type 参数A,但这并不重要,因为A在您的示例中成为一个函数,并且您从不应用该函数,因此???永远不会执行。
关于为什么 Scala 中同时存在“thunk”或无括号函数和空括号函数 ( )存在一些争论。Function0