def f(x: Int): Boolean = (x >= 0 && x < 4)
List(1, 3, 5).map(f) // List(true, true, false)
f // does not compile
为什么可以f在期望函数值的地方使用,即使它本身不是函数值?
def f(x: Int): Boolean = (x >= 0 && x < 4)
List(1, 3, 5).map(f) // List(true, true, false)
f // does not compile
为什么可以f在期望函数值的地方使用,即使它本身不是函数值?
怎么了?
在需要函数类型的地方,f转换为匿名函数(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
为什么首先f不是函数值?
f因为没有定义无参数函数。val g = (x: Int) => (x >= 0 && x < 4)
g
为什么被f接受为函数值?
map需要一个函数类型,并且因为ff和g两者都做同样的事情,所以自动转换是有意义的。 map(f)外观比map(f(_)).