Anonymous functions, also known as lambda expressions, are a powerful feature in Scala. They allow you to create functions without explicitly defining them with a name.
Anonymous functions are inline function literals that can be defined and used on the spot. They are particularly useful when you need a short, one-time-use function as an argument to Higher-Order Functions.
The basic syntax of an anonymous function in Scala is:
(parameters) => expression
For functions with multiple expressions, use curly braces:
(parameters) => {
// Multiple expressions
result
}
val double = (x: Int) => x * 2
println(double(5)) // Output: 10
val numbers = List(1, 2, 3, 4, 5)
val squaredNumbers = numbers.map(x => x * x)
println(squaredNumbers) // Output: List(1, 4, 9, 16, 25)
Anonymous functions are commonly used in:
Scala offers a shorthand notation for even more concise anonymous functions:
val numbers = List(1, 2, 3, 4, 5)
val doubledNumbers = numbers.map(_ * 2)
println(doubledNumbers) // Output: List(2, 4, 6, 8, 10)
Here, the underscore (_) represents each element in the list.
Anonymous functions in Scala provide a powerful tool for writing concise, functional code. They are essential for working with Higher-Order Functions and implementing functional programming patterns. By mastering anonymous functions, you'll be able to write more expressive and efficient Scala code.