def f(x: Int): Boolean = (x >= 0 && x < 4)

List(1, 3, 5).map(f)  // List(true, true, false)
f                     // does not compile

Why can f be used where a function value is expected, even if it is not a function value itself?

1

There are 1 best solutions below

7
On

What is happening?

In places where a function type is expected, f is converted to an anonymous function (x: Int) => f(x).

def f(x: Int): Boolean = (x >= 0 && x < 4)
// f                    // f itself is not a function value
f(_)                    // f(_) is an anonymous function
List(1, 3, 5).map(f)    // f is converted to f(_) in places where a function type is expected
List(1, 3, 5).map(f(_)) // equivalent to last line

Why is f not a function value in the first place?

  • Because the parameterless function f was not defined. A curried (parameterless) function value would work:
val g = (x: Int) => (x >= 0 && x < 4)
g

Why is f accepted as a function value?

  • map expects a function type and because curried and uncurried versions of f f and g both do the same, the automatic conversion makes sense.
  • another advantage is that map(f) has a cleaner look than map(f(_)).
  • a disadvantage of all the automatic and syntactic sugar stuff that is done for you, is that it can be confusing