Jmb Jmb -4 years ago 134
Scala Question

Callback that takes and returns Unit

I have a function that takes a unit callback as a parameter, i.e. a callback that takes and returns

. If I define my function like this:

def myFunction (callback: Unit => Unit) = {

then I get a warning stating that:
Adaptation of argument list by inserting () has been deprecated
. Following this answer, I tried changing my code to:

def myFunction (callback: Unit => Unit) = {

which doesn't work (my callback is not called), or to:

def myFunction (callback: Unit => Unit) = {
callback (());

which works but is ugly. Is there a way to avoid the double parentheses? Maybe by changing the
Unit => Unit
parameter type to something else that means "a function that takes no parameters" instead of "a function that takes one parameter or type

Answer Source

What you're most likely looking for is a function that simply takes no parameters. You also don't need to explicitly type ; at the end of every line.

def myFunction (callback: () => Unit) = callback()

This is not the same as a call-by-name parameter.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download