将一个方法"提升"到"函数"有什么好处?

Man*_*dha 2 scala

我读到"lift"可用于将方法调用提升到函数中.这个例子是

scala> def times2(i: Int) = i * 2
times2: (i: Int)Int
Run Code Online (Sandbox Code Playgroud)

我们通过应用下划线将方法提升为函数

scala> val f = times2 _
f: Int => Int = <function1>

scala> f(4)
res0: Int = 8
Run Code Online (Sandbox Code Playgroud)

这有什么好处?我可以使用f(4)或times2(4)

And*_*kin 5

如果要将其作为参数传递给更高阶函数,则必须取消该方法.例如,如果您有f: Int => Int一个更高阶函数

def higherOrderFunction(f: Int => Int): Int = f(42)
Run Code Online (Sandbox Code Playgroud)

你可以传递f给它.您无法使用方法执行此操作,因为方法不是值.但是,该方法可以提升到一个函数值:

def higherOrderFunction(f: Int => Int): Int = f(42)
def times2(i: Int) = i * 2
val f = times2 _
println(higherOrderFunction(f)) // prints 84
Run Code Online (Sandbox Code Playgroud)

现在,这似乎不是什么大不了的事,因为你可以times2直接写,而不是f在传递它时higherOrderFunction,因为scala会把它变成看起来非常像的东西f.

以下是语法 (times2 _)实际有用的示例:

val times4: Int => Int = (times2 _) andThen (times2 _)
println(times4(100))
Run Code Online (Sandbox Code Playgroud)

这打印400.

关键是这f是一流的公民价值:您可以将其存储在某种数据结构中,或通过网络发送.这就是函数式编程的重点:您可以将函数和闭包传递给更高阶的函数.