Passing function as block of code between curly braces

This is called either a nullary function or a thunk, and is an example of call-by-name evaluation:

You can use nullaries pretty much anywhere you have a parameter list. They are basically just syntactic sugar around zero-argument functions that make them look like ordinary values, and are invoked whenever they are referenced.


def doSomething(op: => Unit) {
doSomething {

is exactly the same as:

def doSomething(op: () => Unit) {
doSomething(() => println("Hello!"))

The one thing to keep in mind with nullaries is they are invoked every time they are referenced, so something like:

def foo(op: => Int) = op + op
foo {

will print “foo” twice.

Edit: To expand on Randall’s comment, one of the big ways that a nullary function differs from a zero-arg function is that nullaries are not first-class values. For example, you can have a List[() => Int] but you cannot have a List[=> Int]. And if you had something like:

def foo(i: => Int) = List(i)

you are not adding the nullary function to the list, only its return value.

Leave a Comment