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?
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?
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?
f
was not defined. A val g = (x: Int) => (x >= 0 && x < 4)
g
Why is f
accepted as a function value?
map
expects a function type and because f
f
and g
both do the same, the automatic conversion makes sense. map(f)
has a cleaner look than map(f(_))
.