先看下面的例子(引自[1]):
def nano() = { println("Go into nano") System.nanoTime } def delayed(t: => Long) = { println("In delayed method") println("Param: "+t) t } def undelayed(t: Long) = { println("In not delayed method") println("Param: "+t) t } 在scala中以call by name方式调用nano:
scala> delayed(nano())
结果为:
In delayed method Go into nano Param: 4475258994017 Go into nano res3: Long = 4475259694720
以普通方式调用nano:
scala> notDelayed(nano())
结果为:
Go into nano In not delayed method Param: 4513758999378 res4: Long = 4513758999378
上述3个method中,delayed()和notdelayed()是caller(调用者),nano()是callee(被调用者)。可以看出当以普通方式调用callee时,nano()会在caller一开始运行的时候被计算一遍,在caller内部用到callee时,只要取出之前得到的结果即可,不会重新执行一遍callee;但Call by Name方式下不会预计算callee,而是严格地在每个使用callee的地点完整运行一遍callee。
[1] David Pollak, Beginning Scala, Apress, 2009, p31