正如我所理解的方法的call-by-name
参数,在将相应的参数表达式传递给方法时不会对其进行求值,而只有当(并且如果)在方法体中使用了参数的值时才会对其求值。
然而,在下面的例子中,这只在前两个方法调用中成立,而在第三个方法调用时不成立,尽管这应该只是第二种情况的语法变体!?
为什么在第三个方法调用中对参数表达式求值?
(我使用Scala2.11.7测试了这段代码)
class Node(x: => Int)
class Foo {
def :: (x: =>Int) = new Node(x) // a right-associative method
def !! (x: =>Int) = new Node(x) // a left-associative method
}
// Infix method call will not evaluate a call-by-name parameter:
val node = (new Foo) !! {println(1); 1}
println("Nothing evaluated up to here")
// Right-associative method call will not evaluate a call-by-name parameter:
val node1 = (new Foo).::({println(1); 1})
println("Nothing evaluated up to here")
// Infix and right-associative method call will evaluate a call-by-name parameter - why??
val node2 = {println(1); 1} ::(new Foo) // prints 1
println("1 has been evaluated now - why??")
2020年编辑:请注意,Scala 2.13不再显示这种令人恼火的行为:val node2 = ...
不再打印任何内容。
这是一个错误。一个旧的,在那个。
参见SI-1980和PR#2852。
链接的拉取请求在使用-Xlint
标志时添加了编译器警告:
<console>:13: warning: by-name parameters will be evaluated eagerly when called as a right-associative infix operator. For more details, see SI-1980.
def :: (x: =>Int) = new Node(x) // a right-associative method
^
只要提到By name参数,就会对其求值。规范中说,正确的关联运算符方法调用是这样评估的:
a op_: b
减温器至:
{ val someFreshName = a; b.op_:(someFreshName) }
// ↑↑↑
// Eval happens here ↑↑↑