The collect
api in collection classes like Sequence
uses a partial function as argument. The isDefinedAt
mechanism of the partial function effectively acts as a filter for the incoming elements and the apply
method acts as the transformer for the element.
Filter and map are fundamental operations in functional programming. My perspective on the collect api is as the hybrid of both together.
Let us take a demonstrative example of a sequence of numbers, only even numbers which need to be again doubled and returned. The way I would have approached is to have a filter
to first filter in only the even numbers with a predicate
like i % 2 ==0
, and then a map
function to double the value like i => i * 2
val seqOne: Seq[Int] = Seq(1,2,3,4,5,6)
val resultOne = seqOne.filter(_%2==0).map(_*2)
println(resultOne)
List(4, 8, 12)
The equivalent collect approach would be as below
val doubleIfEven = new PartialFunction[Int,Int] {
def isDefinedAt(x : Int) = x % 2 == 0
def apply(x : Int) = x * 2
}val result = seqOne.collect(doubleIfEven)
println(result)
List(4, 8, 12)