为什么 scala 在打印它被调用的行之前调用传递给 println 的方法? [英] Why does scala call the method passed to println before printing the line it is called in?
问题描述
程序看起来像这样......
The program looks like this ...
object Delay{
def main(args: Array[String]){
delayed(time())
}
def time()={
println("Getting time in nanoseconds : ")
System.nanoTime
}
def delayed(t: => Long)={
println("In delayed Method")
println("Param : "+t)
}
}
输出是...
In delayed Method
Getting time in nanoseconds :
Param : 139735036142049
我的问题是为什么Param :"这个词打印在Getting time ..."之后而不是像,
My question is why does the word "Param :" print after the "Getting time ..." and not like,
In delayed Method
Param :
Getting time in nanoseconds : 139735036142049
推荐答案
之所以看到这个执行顺序,是因为 t
是一个 by-name 参数您的代码:
The reason why you see this execution order, is because t
is a by-name parameter in your code:
def delayed(t: => Long)
如果您使用 by-value 参数定义了 delayed
方法,如下所示:
If you defined your delayed
method with a by-value parameter like so:
def delayed(t: Long)
time()
函数会在调用延迟
之前被评估,而你会得到以下输出:>
Getting time in nanoseconds :
In delayed Method
Param : 139735036142049
诀窍是按名称参数仅在使用时被调用,并且每次被使用.来自 Scala 文档:
The trick is that by-name parameters are called only when they're used, and every time they're used. From the Scala docs:
By-name 参数仅在使用时进行评估.它们与按值参数形成对比.
By-name parameters are only evaluated when used. They are in contrast to by-value parameters.
按名称参数的优点是,如果它们不在函数体中使用,则不会对其进行评估.另一方面,按值参数的优点是它们只计算一次.
By-name parameters have the advantage that they are not evaluated if they aren’t used in the function body. On the other hand, by-value parameters have the advantage that they are evaluated only once.
这篇关于为什么 scala 在打印它被调用的行之前调用传递给 println 的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!