No boilerplate
Boilerplate code consists sections of the same code written again and again. For example, writing loops is boilerplate, as is writing getters and setters for private
class members.
As the preceding code shows, the loop is implicit:
scala> List(1, 2, 3, 4, 5) partition(_ % 2 == 0) res3: (List[Int], List[Int]) = (List(2, 4),List(1, 3, 5))
We just wish to separate the odd and even numbers. So we just specify the criteria via a function, an anonymous function in this case. This is shown in the following image:
What is boilerplate? It is a for loop, for example. In the imperative world, we code the loop ourselves. We need to tell the system how to iterate over a data structure.
Isn't Scala code just to the point? We tell what we need and the loop is implied for us. No need to write a for loop, no need to invent a name for the loop variable, and so on. We just got rid of the boilerplate.
Here is a Clojure snippet that shows how to multiply each element of a vector by 2
:
user=> (map * (repeat 2) [1 2 3 4 5]) (2 4 6 8 10)
The map
function hides the loop from us. Then (repeat 2)
function call generates an infinite sequence.
So we are just saying this: for the input sequence [1 2 3 4 5]
, create another lazy sequence of 2's. Then use the map
function to multiply these two sequences and output the result. The following figure depicts the flow:
Compare this with an imperative language implementation. We would have needed a loop and a list to collect the result. Instead, we just say what needs to be done.