什么是Scala中的函数字面量? [英] What is a function literal in Scala?
问题描述
什么是Scala中的函数文字,什么时候应该使用它们?
What is a function literal in Scala and when should I use them?
推荐答案
函数文字是定义一个函数。当你想将一个函数作为参数传递给一个方法时(特别是像折叠或过滤器操作这样的高阶函数),但不想定义一个单独的函数时,这非常有用。函数文字是匿名的 - 默认情况下它们没有名称,但是可以通过将它们绑定到变量来给它们起个名字。函数literal的定义如下:
A function literal is an alternate syntax for defining a function. It's useful for when you want to pass a function as an argument to a method (especially a higher-order one like a fold or a filter operation) but you don't want to define a separate function. Function literals are anonymous -- they don't have a name by default, but you can give them a name by binding them to a variable. A function literal is defined like so:
(a:Int, b:Int) => a + b
您可以将它们绑定到变量:
You can bind them to variables:
val add = (a:Int, b:Int) => a + b
add(1, 2) // Result is 3
之前,函数文字对于作为参数传递给高阶函数很有用。它们对于定义嵌套在其他函数中的单行或辅助函数也很有用。
Like I said before, function literals are useful for passing as arguments to higher-order functions. They're also useful for defining one-liners or helper functions nested within other functions.
Scala之旅为函数文字(他们称之为匿名函数)提供了很好的参考。
A Tour of Scala gives a pretty good reference for function literals (they call them anonymous functions).
这篇关于什么是Scala中的函数字面量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!