2

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 ?

f_s
  • 113
  • 10
  • 2
    I'd strongly advise against any infix operators or implicit methods on the integers. Those are features that should only be used in the rarest cases with extreme caution by experienced library authors, and only if there is an established tradition of using such notation. All attempts to use it in ordinary code only contribute to the rumors that Scala has a difficult syntax (whereas it actually has rather simple syntax, but too many users who don't know where to stop). Does syntax have anything to do with the problem that you're trying to solve? If not - don't waste your time on it. – Andrey Tyukin May 07 '21 at 11:25
  • 1
    Of course your is a really good advice. Anyway, my question concerns leaning and experimenting with Scala syntax. – f_s May 07 '21 at 13:47

1 Answers1

3

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.

Mario Galic
  • 47,285
  • 6
  • 56
  • 98