[ACCEPTED]-What is a function literal in Scala?-functional-programming

Accepted answer
Score: 84

A function literal is an alternate syntax 16 for defining a function. It's useful for 15 when you want to pass a function as an argument 14 to a method (especially a higher-order one 13 like a fold or a filter operation) but you 12 don't want to define a separate function. Function 11 literals are anonymous -- they don't have 10 a name by default, but you can give them 9 a name by binding them to a variable. A 8 function literal is defined like so:

(a:Int, b:Int) => a + b

You 7 can bind them to variables:

val add = (a:Int, b:Int) => a + b
add(1, 2) // Result is 3

Like I said before, function 6 literals are useful for passing as arguments 5 to higher-order functions. They're also 4 useful for defining one-liners or helper 3 functions nested within other functions.

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

Score: 21

It might be useful to compare function literals 13 to other kinds of literals in Scala. Literals are 12 notational sugar for representing values of some types the 11 language considers particularly important. Scala has integer 10 literals, character literals, string literals, etc. Scala 9 treats functions as first class values representable 8 in source code by function literals. These 7 function values inhabit a special function type. For 6 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 5 values, that is, without bounding them to 4 a named variable first. This helps make 3 the program more concise and is appropriate 2 when the literal is not meant to be reusable. For 1 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)

More Related questions