Having started on functional programming from JavaScript, after transforming and filtering elements in a list/iterator, the approach that I tried to extract the final filtered value out of the iterator was to try reduce operations. Instead, what I needed was the headOption
method.
A simple example of transforming a list and extracting one value out, and additionally being able to specify a default value if nothing is left after the filtering exercise.
println(List(1,2,3)
.map(_*2)
.filter(_%3 ==0)
.headOption
.getOrElse(100)
)
6
If we had started off with a list that would filter out everything, then we should get the default of 100.
println(List(1,2)
.map(_*2)
.filter(_%3 ==0)
.headOption
.getOrElse(100)
)
100