Ad space (banner)
Lesson 16 / 20

Higher-order functions, map and filter

This lesson covers higher-order functions — functions that take other functions as arguments — and the list operations map and filter.

map builds a new list by transforming each element, and filter builds a new list of only the elements that match a condition. Neither changes the original list.

The sample code keeps only the even numbers with numbers.filter(_ % 2 == 0) and multiplies each by ten with .map(_ * 10). The _ is shorthand for "the element itself".

A common early stumble is what that _ symbol means. Writing _ * 10 instead of x => x * 10 is a piece of Scala shorthand that feels odd at first and reads very naturally once you are used to it.

In professional work, combining map and filter is considered more idiomatic than handling elements one at a time in a for loop, and the same thinking carries over to data processing in Apache Spark.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Scala directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)