0

I would like to know, which is the difference between these:

object Something {
 def apply(op: => Unit) {}
}

and this:

object Something {
 def apply(op:() => Unit) {}
}

because when I call them, it requires me to write:

  • in first case: Something { afunction() }
  • in second case: Something { () => afunction() }
Valerin
  • 465
  • 3
  • 19

1 Answers1

1

First is a parameter passed by name, the second is a lambda expression with 0 parameters. There is no actual difference in meaning that both are not evaluating op til its called, but the first one may be less safe because user of your function may not know that it will be lately evaluated or not evaluated at all.

So, if you're expecting some side-effects inside passed parameter like Something({println("aaa"); 5}) and want user (who may not look at signature and just got your function from some example) to know that his code may not be executed - it's better to use Something(() => {println("aaa"); 5})

See more:

By-name parameter vs anonymous function

What's the difference between => , ()=>, and Unit=>

Community
  • 1
  • 1
dk14
  • 22,206
  • 4
  • 51
  • 88