prassee prassee - 8 months ago 48
Scala Question

What is a function literal in 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.

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