J Person J Person - 1 month ago 7
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 = {
f(1)
f(1)
}

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


twice(oneParam)


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

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

def noParams() = println(2)

twice(noParams)


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

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)

Comments