[英]Why can a scala function name be used where a function value is expected, when 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?为什么
f
可以在预期 function 值的地方使用,即使它本身不是 function 值?
What is happening?怎么了?
In places where a function type is expected, f
is converted to an anonymous function (x: Int) => f(x)
.在需要 function 类型的地方,
f
被转换为匿名 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
首先不是 function 值?
f
was not defined.f
。 A
val g = (x: Int) => (x >= 0 && x < 4)
g
Why is f
accepted as a function value?为什么
f
被接受为 function 值?
map
expects a function type and because
f
f
and g
both do the same, the automatic conversion makes sense. map
需要一个 function 类型,因为 f f
和g
f
咖喱和非咖喱版本
map(f)
has a cleaner look than map(f(_))
.map(f)
的外观比map(f(_))
更干净。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.