apply 函数中的参数f 是一个Funcion1,它采用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 中作为Function0[Int] 出现(因此Scala 隐含地将按名称调用或“thunk”参数视为没有参数的函数)。您可以再次验证这一点:
def const[A](ignored: A): Int = if (ignored.isInstanceOf[Function0[_]]) 1 else 0
现在Test.res 将给你1(意味着ignored 确实是Function0)。
所以要以不同的方式回答这个问题,const 有一个 A 类型的热切参数,但这并不重要,因为 A 在您的示例中变成了一个函数,而您永远不会应用该函数,因此??? 永远不会被执行。
在 Scala 中有 some debate 与 why there is both 一个“thunk”或无括号函数和一个空括号函数 (Function0)。