问题描述
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()
。