在scala中添加回调作为参数?
我在scala中有以下函数:在scala中添加回调作为参数?,scala,Scala,我在scala中有以下函数: def addAllCosts(costs: List[Int],discount: Int => Int): Int = { var sum = 0 costs.foreach(sum += _) discount(sum) } 我在http akka路由器中这样调用函数: HttpResponse(200, entity= repository.addAllCosts(costs,repository.applyDiscount(23))) appl
def addAllCosts(costs: List[Int],discount: Int => Int): Int = {
var sum = 0
costs.foreach(sum += _)
discount(sum)
}
我在http akka路由器中这样调用函数:
HttpResponse(200, entity= repository.addAllCosts(costs,repository.applyDiscount(23)))
applyDiscount如下所示:
def applyDiscount(sum:Int): Int = {
return sum - discount
}
但是,我得到以下错误:
Error:(45, 94) type mismatch;
found : Int
required: Int => Int
不知道如何解决这个问题?谢谢 applyDiscount是一个Int=>Int函数,但是,您将repository.applyDiscount23作为折扣参数的值传递,该表达式的类型为Int,因为它是将函数应用于值23的结果,而不是预期的Int=>Int类型
不确定值23来自何处,但这至少应该是一种编译方式,您只需传递对该方法的引用而不应用它:
HttpResponse(200, entity= repository.addAllCosts(costs, repository.applyDiscount))