← Back to Scala Course | Chapter 9: Functional Programming | Lesson 3 of 8

Anonymous Functions

In this page:

  1. Anonymous Functions

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

markup
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)
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.