Functional programming in Scala
As said earlier, functional programming requires a different mindset to imperative programming. We will look at several functional-programming-related topics here:
- Iterating through collections using functions
- The map, filter, and reduce design pattern
- Currying
Iterating through collections using functions
In functional programming, it is unusual to use both for
or while
loops to iterate through arrays and collections and process each item inside the loop's body. Instead, a method is called on the array or collection instance, which internally iterates through the array or collection. The method takes a lambda function as a parameter and ensures that the function is called for each item:
var a = List[Int](5, 10, 15, 20, 25) a.foreach((x: Int) => println("%03d".format(x)))
This will print 005
, 010
, 015
, 020
, and 025
. It uses the format
method of Java's java.lang.String
class to ensure that the printed integer has up to three leading zeroes.