简体   繁体   English

为什么ZBAAD2C48E6FBC14C61337D0B2578221Z ZC1C1C1C425268E683851AB5074C174C174F14F14F14F使用ZC1C425268E IS74C5174C174C174C174C174C174C174C14C174C14C174C14C174C14C174C14C174C14C174C14C174C14C14C14C14C14C14C14C14C14C14C14FAB14C14F14FAB14C14FAB14C14F14F14F14F14F14F14F14F14C14C14AB

[英]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 值?

  • Because the parameterless function f was not defined.因为没有定义无参数的 function f A curried (parameterless) function value would work: 咖喱 (无参数) function 值将起作用:
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 curried and uncurried versions of f f and g both do the same, the automatic conversion makes sense. map需要一个 function 类型,因为 f fg f咖喱和非咖喱版本 都做同样的事情,自动转换是有意义的。
  • another advantage is that map(f) has a cleaner look than map(f(_)) .另一个优点是map(f)的外观比map(f(_))更干净。
  • a disadvantage of all the automatic and syntactic sugar stuff that is done for you, is that it can be confusing为您完成的所有自动和语法糖的缺点是它可能会令人困惑

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM