Scala 中 call by name & call by value 的区别
call by value:会先计算参数的值,然后再传递给被调用的函数
call by name:参数会到实际使用的时候才计算
定义方法
def return1():Int = { println("calling...") 1 } def callByValue(x: Int) = { println("x1=" + x) println("x2=" + x) } def callByName(x: =>Int) = { println("x1=" + x) println("x2=" + x) }
调用方法,比较输出
scala> callByValue(return1()) calling... x1=1 x2=1 scala> callByName(return1()) calling... x1=1 calling... x2=1