Scala: Function0 vs by-name parameters

Viewed 1083

Can anyone give a definitive answer on how by-name parameters => T and Function0 parameters () => T are transformed into one another by the Scala compiler? I know they are not the same, but the difference is very subtle as they can be interchangeably used in many scenarios.

Example: if I define

def someFunction: Int = 2
def f(x: => Int): Unit = println(x)

then I can successfully call

f(2)
f(someFunction)

How is () => Int an acceptable replacement for => Int?

More generally, is () => T a universally acceptable replacement for a by-name => T parameter?

Also, please correct me if I'm wrong on the following reasoning: => T is never an acceptable replacement for () => T because the first is a value type (T), the other is a function type. That is, if I have def f(x: () => Int), I'll never be able to pass an Int, or a lazy Int (doesn't even make sense anyway as there are no lazy types).

1 Answers
Related