Scala 中的函数字面量是什么? [英] What is a function literal in Scala?

查看:26
本文介绍了Scala 中的函数字面量是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是 Scala 中的函数字面量,我应该什么时候使用它们?

What is a function literal in Scala and when should I use them?

推荐答案

函数字面量是定义函数的另一种语法.当您想将函数作为参数传递给方法(尤其是像折叠或过滤操作这样的高阶函数)但又不想定义单独的函数时,它很有用.函数文字是匿名的——默认情况下它们没有名称,但您可以通过将它们绑定到变量来为它们命名.函数字面量定义如下:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆