Anonymous functions are unnamed functions that can be written as little snippets of code. They are useful when we want to write a function inline without any explicit definitions.
To demonstrate how anonymous functions are used in Scala, we will be using some of the inbuilt functions such as filter
and map
on lists.
In the following program, we first create a list using the List
class and then calling the range
method. As a result, the list example
contains a list of integers in the range from 1 to 10:
val example = List.range(1,10)println(example)
map
Now, we will use an anonymous function that doubles every element of the list using the map
method:
val example = List.range(1,10)val doubled = example.map(_ * 2)println(doubled)
In the code above, _ * 2
is an anonymous function. This is a concise way of saying, “Multiply the element by 2”. We could have defined the anonymous function as an explicit definition as well:
example.map((i: Int) => i * 2)
The _
symbol is used as a wildcard character in Scala. In our example, it simply means "An element from the list of integers example
".
filter
Similar to map
, we can use anonymous functions in the filter
method as well.
The following program shows how we can use an anonymous function to filter out numbers greater than 3 in a list:
val example = List.range(1,10)val filtered = example.filter(_ > 3)println(filtered)
The expression _ > 3
in line 2 is the anonymous function in the code above. The filter
method expects a function that takes an integer and returns a boolean value. So, it filters out the numbers for which the function returns true
. An explicit definition of the anonymous function above would be:
def greaterThanThree(i:Int):Boolean = (i > 3)
val filtered = example.filter(greaterThanThree)
Free Resources