3 回答
TA贡献1898条经验 获得超8个赞
Int
.
def something() = { println("calling something") 1 // return value}
Int
x: Int
x: => Int
).
def callByValue(x: Int) = { println("x1=" + x) println("x2=" + x)}def callByName(x: => Int) = { println("x1=" + x) println("x2=" + x)}
scala> callByValue(something())calling something x1=1x2=1scala> callByName(something())calling something x1=1calling something x2=1
something()
TA贡献1818条经验 获得超8个赞
def test (x:Int, y: Int)= x*x
test (2,3)
test (3+4,8)
test (7,2*4)
test (3+4, 2*4)
TA贡献1863条经验 获得超2个赞
我认为最好把“逐名”看作是语法糖。解析器只是将表达式封装在匿名函数中,以便在以后使用时调用它们。
实际上,而不是定义
def callByName(x: => Int) = { println("x1=" + x) println("x2=" + x)}
和跑步:
scala> callByName(something())calling something x1=1calling something x2=1
你也可以写:
def callAlsoByName(x: () => Int) = { println("x1=" + x()) println("x2=" + x())}
并按以下方式运行,效果相同:
callAlsoByName(() => {something()})calling something x1=1calling something x2=1
添加回答
举报