如何解决如何在scala中声明隐式类的方法中的默认参数
implicit class myclass(n:Int ){
private def mapCombineReduce(map : Int => Double,combine: (Double,Double) => Double,zero: Double )(a:Int,b:Double): Double =
if( a > b) zero else combine ( map(a),mapCombineReduce(map,combine,zero)(a+1,b) )
var default_value_of_z : Int = 0
def sum( z : Int = default_value_of_z) = mapReduce( x=>x,(x,y) => x+y+z,0)(1,n)
def ! = mapCombineReduce( x=> x,y) => x*y,1)(1,n)
}
4 !
4 sum 1 //sum the elements from 1 to 7 and each time combine the result,add 1 to the result.
4 sum
scala 2.12 有没有办法在 myclass 中没有双重声明 sum 方法的情况下运行 4 sum
?
解决方法
否,因为只有在参数列表为 provided 时才使用默认参数
def f(x: Int = 1) = x
f // interpreted as trying to do eta-expansion
事实上,从 Scala 3 开始,它确实会eta-expand
scala> def f(x: Int = 1) = x
def f(x: Int): Int
scala> f
val res1: Int => Int = Lambda$7473/1229666909@61a1990e
因此,在您的情况下,您必须编写带有参数列表的 4.sum()
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。