J Person J Person - 1 year ago 64
Scala Question

How to distinguish between a reference to a function with no paramters and a call to that function in Scala?

Suppose I have a function definition like

def twice(f: Int => Unit): Unit = {

def oneParam(i: Int) = println(1)


I can pass around oneParam by name, but if I do the same with a no parameter function:

def twice(f: Unit => Unit): Unit = {

def noParams() = println(2)


I get a compiler error because even though I declared noParams with an empty paramter list the compiler thinks I'm trying to call the function with no parameter list. How can I pass around this function then?

Answer Source

Your function is declared wrong. Unit => Unit is not a function, that takes no params, it's a function that takes one parameter of type Unit.

Try declaring it like this instead: def twice(f: () => Unit)

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