Felipe
Felipe

Reputation: 7633

Scala Higher order functions in details

I am learning Scala Higher Order Functions. I am studying an example that is a class; there is one method that receives a function and a value parameter and returns a value. The function is p: Tweet => Boolean and the method implementation is further below. I want to know where is the implementation of the p function.

class NonEmpty(elem: Tweet, left: TweetSet, right: TweetSet) extends TweetSet {
  def filterAcc(p: Tweet => Boolean, acc: TweetSet): TweetSet = {
    if (p(elem)) {
      left.filterAcc(p, acc.incl(elem))
      right.filterAcc(p, acc.incl(elem))  
    } else {
        left.filterAcc(p, acc)
        right.filterAcc(p, acc)
    }                    
}

Upvotes: 2

Views: 338

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149628

I wonder to know where is the implementation of the p function

If you go further down in the class definition, you'll see one of the implementations of p in union

def union(that: TweetSet): TweetSet = {
  this.filterAcc(elem => true, that)
}

With Higher Order Functions, the caller of the method is the one in charge of providing an implementation of the function that he wishes to run. You can take a look at common use cases such as map, flatMap, filter, etc on Scalas collection library.

Upvotes: 2

Related Questions