Search code examples
scalascala-compiler

How to declare in scala a default param in a method of an implicit class


In order to use infix notation, I have the following example of scala code.

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, (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

Is there any way in scala 2.12 to run 4 sum without have a double declaration of the sum method inside myclass ?


Solution

  • No, because default arguments are only used if argument list is provided

    def f(x: Int = 1) = x
    f // interpreted as trying to do eta-expansion
    

    In fact starting Scala 3 it will indeed eta-expand

    scala> def f(x: Int = 1) = x
    def f(x: Int): Int
    
    scala> f                                                                                                                                                    
    val res1: Int => Int = Lambda$7473/1229666909@61a1990e
    

    so in your case you will have to write 4.sum() with argument list present.