Why does scala call the method passed to println before printing the line it is called in?

前端 未结 3 702
我在风中等你
我在风中等你 2021-01-23 18:09

The program looks like this ...

object Delay{

    def main(args: Array[String]){
        delayed(time())
    }

    def time()={
        println(\"Getting time          


        
3条回答
  •  醉梦人生
    2021-01-23 18:51

    The reason why you see this execution order, is because t is a by-name parameter in your code:

    def delayed(t: => Long)
    

    If you defined your delayed method with a by-value parameter like so:

    def delayed(t: Long)
    

    the time() function would have been evaluated before the call to delayed, and you would get the following output instead:

    Getting time in nanoseconds : 
    In delayed Method
    Param : 139735036142049
    

    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 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.

提交回复
热议问题