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

Anonymous Functions

An anonymous function is a tiny nameless helper written on the spot, like a quick note of instructions. It is handy for short jobs such as doubling each number.

In this page:

  1. Anonymous Functions
Syntax
scala
val function_name = (param: Type) => expression
val other = (a: Type, b: Type) => expression
collection.map(_ * 2)

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)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using _ twice like numbers.map(_ * _) and expecting one value, when each underscore stands for a different parameter.
  2. Using _ inside a nested expression such as map(foo(_ + 1)), where it expands to the wrong function.
  3. Writing n -> n * n instead of n => n * n, when -> makes a tuple.
🔒

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.