Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a function literal in Scala?

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

like image 208
prassee Avatar asked Mar 09 '11 03:03

prassee


People also ask

What is literal function go?

A function literal is a function declared inline without a name. In all other languages, this is called an anonymous function.

What is function literal in Java?

In simple words, Literals in Java is a synthetic representation of boolean, numeric, character, or string data. It is a medium of expressing particular values in the program, such as an integer variable named ''/count is assigned an integer value in the following statement.

What is an anonymous function Scala?

In Scala, An anonymous function is also known as a function literal. A function which does not contain a name is known as an anonymous function. An anonymous function provides a lightweight function definition. It is useful when we want to create an inline function.

What are higher order functions in Scala?

In Scala, a higher-order function is a function which takes another function as an argument. A higher-order function describes "how" the work is to be done in a collection. Let's learn the higher order function map. The map applies the function to each value in the collection and returns a new collection.


1 Answers

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).

like image 176
Rafe Kettler Avatar answered Sep 18 '22 14:09

Rafe Kettler