What is a function literal in Scala?

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)