Anonymous Functions
In this page:
Anonymous Functions
An anonymous function (or "lambda") is a function value written inline without a name, using (params) => expression syntax, commonly passed directly to a higher-order function like map. The placeholder underscore _ offers an even more compact shorthand for simple single-argument cases, like _ * 2. Anonymous functions avoid the ceremony of a full named def for short, one-off logic.
Note: The underscore shorthand, like numbers.map(_ * 2), is Scala's most concise way to write a simple single-parameter anonymous function.
Example: Anonymous Functions
object Main extends App {
val numbers = List(1, 2, 3, 4)
val squared = numbers.map(n => n * n)
val doubled = numbers.map(_ * 2)
println(squared)
println(doubled)
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: