1

I was recently playing with a piece of code which relies heavily on function parameters and noticed the following behaviour which I can't quite explain to myself:

// first, a few methods
def a(x: => Any) {}
def b(x:() => Any) {}
// then some helpers
def x = {}
def y() = {}
// these execute the possible combinations
a(x)
b(y)
a(y)
b(x)

The first three work as expected, but the fourth one fails. REPL output for it is

<console>:10: error: type mismatch;
 found   : Unit
 required: () => Any
              b(x)
                ^

For me x and y look the same but they obviously aren't. At first I thought it was some kind of property access instead of method being referenced but I couldn't reason that through since a(y) seems to work just fine - in other words, I can't see the symmetry between the operations.

So, what am I missing?

Esko
  • 29,022
  • 11
  • 55
  • 82
  • Duplicate or not, I do have to say that Patrik's answer is lighter on the reader than the answers in the linked question. – Esko May 27 '13 at 08:19

1 Answers1

2

They are quite different and as usual (annoying, I know) the compiler is right.

def a(x: => Any) - Function that takes a parameter x by name where x is Any and returns unit, so the full definition would be: def a(x: => Any) : Unit.

def b(x: () => Any) - Function that takes a parameter x by value, where x is a function () => Any.

def x = {} is equivalent to def x : Unit = {}

def y() = {} is equivalent to def y(): Unit = {} (Which is a function mapping no parameters, i.e. (), to Unit, i.e. Any).

So, the fourth one fails, since x is not a function mapping no parameters to Any, it is just a property returning Unit.

PatrikAkerstrand
  • 45,315
  • 11
  • 79
  • 94