Nespony
Nespony

Reputation: 1371

Adding callback as a parameter in scala?

I have the below function in scala:

 def addAllCosts(costs: List[Int],discount: Int => Int): Int = {
var sum = 0
costs.foreach(sum += _)
discount(sum)
}

I am invoking the function like so in a http akka router:

HttpResponse(200, entity= repository.addAllCosts(costs,repository.applyDiscount(23)))

applyDiscount looks like this:

def applyDiscount(sum:Int): Int = {
    return sum - discount
  }

However, I am getting the following error:

Error:(45, 94) type mismatch;
 found   : Int
 required: Int => Int

Not sure how to resolve this? Thanks!

Upvotes: 0

Views: 47

Answers (1)

Tzach Zohar
Tzach Zohar

Reputation: 37832

applyDiscount is an Int => Int function, however, you're passing repository.applyDiscount(23) as the value of the discount argument, and that expression has the type Int (because it's the result of applying the function to the value 23), instead of the expected type Int => Int.

Not sure where the value 23 comes from, but this should at least compile of you just pass a reference to the method without applying it:

HttpResponse(200, entity= repository.addAllCosts(costs, repository.applyDiscount))

Upvotes: 1

Related Questions