Scala Call By Name Confusion

前端 未结 3 1266
渐次进展
渐次进展 2021-01-05 16:48

I am working on some call by name examples using the REPL and running the same examples in Eclipse.

Here is what in Eclipse:
Scenario 1:

val fun         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-05 17:14

    There is no difference in the output. The difference is in what you want. From Eclipse you ran two things:

    val funct = {println("Calling funct")} // prints Calling funct here
    takesFunct(funct)
    
    def takesFunct(f: => Unit)
    {
       val b = f
    }
    

    and

    val funct = {println("Calling funct")} // prints Calling funct here
    takesFunct({println("Calling funct")}
    
    def takesFunct(f: => Unit)
    {
       val b = f                           // prints Calling funct here
    }
    

    On the REPL, the same thing happened according to your own logs:

    scala> def takesFunct(f: => Unit)
    {
      val b = f
    }
    takesFunct: (f: => Unit)Unit
    
    scala> val funct = {println("Calling funct")}
    Calling funct
    funct: Unit = ()
    
    scala> takesFunct(funct)
    // No Output
    

    Now, in the second scenario all you did was this:

    scala> takesFunct({println("Calling funct")}
    Calling funct
    

    Since you did not repeat the val funct assignment, which was still present in Eclipse's second scenario, it did not print a message.

    Note that

    val funct = {println("Calling funct")}
    

    is, as a practical matter, equivalent to

    println("Calling funct")
    val funct = ()
    

提交回复
热议问题