All lessons

Power Tools: Anonymous Functions & Collection Methods

10 min · Scala

Write inline anonymous functions and transform lists with map and filter.

Scala · Power Tools: Anonymous Functions & Collection Methods0/5 cleared

Enemy 1 of 5

Functions without names

Every function you've written so far had a name given by `def`. But often you need a small, one-off function just to hand to something else — for example, "the rule to apply to each element of a list" — and giving it a permanent name would just clutter the program. An anonymous function (sometimes called a lambda) is a function value written inline, with no `def` and no name: `(params) => expression`.

`val square = (n: Int) => n * n` stores an anonymous function in a `val` named `square`, and it's called exactly like any other function: `square(6)`. The only syntactic difference from a named `def` is the `=>` arrow separating the parameter list from the body, instead of `=`.

You
Binary Treant

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: 36