Scala中回调作为参数传递报错:类型不匹配问题排查
解决Scala类型不匹配错误:
found : Int required: Int => Int 嘿,我来帮你捋清楚这个问题~
首先,咱们先拆解一下错误的根源:
你的addAllCosts函数第二个参数要求的是一个函数类型Int => Int(也就是接收Int、返回Int的函数),但你调用时传的repository.applyDiscount(23)是直接执行了这个方法,得到的是一个Int值,这就导致了类型不匹配——编译器要函数,你给了个数字,当然会报错啦。
你的代码问题点具体分析:
addAllCosts的签名:def addAllCosts(costs: List[Int],discount: Int => Int): Int,第二个参数discount是函数类型- 你调用时写的
repository.applyDiscount(23):这是把23作为sum参数传入applyDiscount,直接计算出了一个Int结果,而不是传递函数本身
解决方案(三种选其一即可)
方案1:修改applyDiscount为返回函数的方法(推荐,方便复用折扣逻辑)
把applyDiscount改成生成折扣函数的方法,让它接收折扣金额,返回一个处理sum的函数:
def applyDiscount(discountAmount: Int): Int => Int = { sum => sum - discountAmount }
这样再调用repository.applyDiscount(23)时,就会返回一个Int => Int的函数(输入sum,输出sum-23),完全符合addAllCosts的参数要求,你的调用代码不用改。
方案2:直接传递匿名函数
如果只是临时用一次23的折扣,不想修改方法,可以直接在调用时写匿名函数:
HttpResponse(200, entity = repository.addAllCosts(costs, sum => sum - 23))
方案3:传递函数引用(如果折扣值是类的固定字段)
如果你的applyDiscount原本是依赖类里的固定discount字段(比如类成员变量),那你只需要传递函数本身,不要加括号调用:
// 假设applyDiscount的定义是依赖类的discount字段 def applyDiscount(sum: Int): Int = sum - discount // 调用时传递函数引用,而非执行它 HttpResponse(200, entity = repository.addAllCosts(costs, repository.applyDiscount))
内容的提问来源于stack exchange,提问作者Nespony
相关产品推荐
相关产品推荐

