What is a function literal in Scala and when should I use them?
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 typeLiterals 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 => Int) = (x: Int) => x > two
List(one,two,three).filter(greaterThan2)