Scala的By-Name参数

scala函数的参数可以是一般的数值,也可以是一个函数。例如:

scala> def time() = {
     | println("Getting time in nano seconds")
     | System.nanoTime
     | }
time: ()Long

scala> def delayed(t: Long)={
     | println("In delayed method")
     | println("Param: " + t)
     | }
delayed: (t: Long)Unit

scala> delayed(time())
Getting time in nano seconds //先执行了time函数
In delayed method
Param: 31173999406389

从结果的打印可以看到,在向delayed函数传入time函数的时候就已经调用了time函数,所以先打印了Getting time in nano seconds。但是开发者往往是想在真正使用的时候才去执行计算,所以scala提供了一种By-Name参数形式,即参数定义的时候使用t: =>的形式,例如:

scala> def delayed(t: =>Long)={ //注意:和=>之间一定要有空格
     | println("In delayed method")
     | println("Param: " + t)
     | }
delayed: (t: => Long)Unit

scala> delayed(time())
In delayed method //先执行的delayed,再调用的time
Getting time in nano seconds
Param: 31694489357969

你可能感兴趣的:(Scala的By-Name参数)