Confused with () => operator

65 views
Skip to first unread message

Aakash Sharma

unread,
Jul 18, 2016, 4:00:39 PM7/18/16
to scala-user
Hello All,

I have a code snippet:-

def afterDelay(delay: Double)(block: => Unit) {
    val item = WorkItem(currentTime + delay, () => block)
    agenda.enqueue(item)
  }

Can anyone please tell me what is "block: => Unit"? Is it a parameter or a return type?
And how does the function WorkItern work? Specifically, what does the second parm "() => block" mean?

Thanks

James Percent

unread,
Jul 20, 2016, 7:54:41 PM7/20/16
to scala-user
I think I can help on this one! It's lambda stuff. Passing a function around like a variable. I'm not an expert, especially w.r.t terminology. But I hope I can help.

There's some function currying going on there as well, I believe, so you'll want to look up that I think, but the things confusing you were not directly related to that I think.

For your specific questions, I believe the following example might be helpful. The code below wraps try/catch statements so I don't have to have try/catch in every method. I simply put it in 1 method, that accepts a function as a parameter. 


  def resume():Unit = {
    return wrapTryCatchUnit(()=>server.resume())
  }
  private def wrapTryCatchUnit(lambdaFunc:() => Unit): Unit = {
    try {
      lambdaFunc()
    } catch Utilities.safely {
      case ex: Throwable => {
        ex.printStackTrace()
        throw ex
      }
    }
  }


Consider the following

def function(myvar: Int) = myvar + 1

Now consider calling this:

function(10)

The resume method below calls wrapTryCatchUnit passing it:
 
()=>server.resume()

This is equivalent to function(10), where ()=> server.resume() is a lambda function passed to wraptrycatchunit.

Now consider:
 private def wrapTryCatchUnit(lambdaFunc:() => Unit)

The lambdaFunc:() => Unit is how you declare the lambda signature. It's equivalent to myvar: Int in function(myvar: Int).

Finally to execute the function you do:

lambdaFunc() as is done in the try statement below.

Hope this helps!

satorg

unread,
Jul 21, 2016, 4:27:34 PM7/21/16
to scala-user

Can anyone please tell me what is "block: => Unit"? Is it a parameter or a return type?

This is so-called "by name parameter" – it can be thought as the special case of lambda without parameters.

And how does the function WorkItern work? Specifically, what does the second parm "() => block" mean?

This means that WorkItem expects a regular lamba without parameters which should have type "() => Unit" or "() => Any" or something like these two.
The expression "() => block" is necessary to convert the by name parameter "block" to the regular lambda of type "() => ..." which is actually expected by WorkItem.
Reply all
Reply to author
Forward
0 new messages