gpt4 book ai didi

scala - 如果方法是中缀和右关联的,为什么 Scala 会评估按名称调用参数的参数?

转载 作者:行者123 更新时间:2023-12-04 02:01:45 24 4
gpt4 key购买 nike

据我了解 call-by-name方法的参数,相应的参数表达式不会在将其传递给方法时进行计算,而只会在(以及如果)方法体中使用参数的值时进行计算。
但是,在下面的示例中,这仅在前两个方法调用中成立,而在第三个中不成立,尽管它应该只是第二种情况的语法变体!?
为什么在第三个方法调用中评估参数表达式?
(我使用 Scala 2.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 = ...不再打印任何东西。

最佳答案

每当提及按名称参数时,都会对其进行评估。 The spec says右关联运算符方法调用的评估方式如下:

a op_: b

脱糖:
{ val someFreshName = a; b.op_:(someFreshName) }
// ↑↑↑
// Eval happens here ↑↑↑

关于scala - 如果方法是中缀和右关联的,为什么 Scala 会评估按名称调用参数的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33656557/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com