开发者

What is a function literal in Scala?

What is a function lit开发者_StackOverfloweral 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.

A Tour of Scala gives a pretty good reference for function literals (they call them anonymous functions).


It might be useful to compare function literals to other kinds of literals in Scala. Literals are notational sugar for representing values of some types the language considers particularly important. Scala has integer literals, character literals, string literals, etc. Scala treats functions as first class values representable in source code by function literals. These function values inhabit a special function type. For example,

  • 5 is an integer literal representing a value in Int type
  • 'a' is a character literal representing a value in Char type
  • (x: Int) => x + 2 is a function literal representing a value in Int => Int function type

Literals are often used as anonymous values, that is, without bounding them to a named variable first. This helps make the program more concise and is appropriate when the literal is not meant to be reusable. For example:

List(1,2,3).filter((x: Int) => x > 2)

vs.

val one: Int = 1
val two: Int = 2
val three: Int = 3
val greaterThan2: Int => Boolean = (x: Int) => x > two
List(one,two,three).filter(greaterThan2)


Programming in Scala, Third Edition

8.3 FIRST-CLASS FUNCTIONS

A function literal is compiled into a class that when instantiated at runtime is a function value.[2] Thus the distinction between function literals and values is that function literals exist in the source code, whereas function values exist as objects at runtime. The distinction is much like that between classes (source code) and objects (runtime).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜