sweetyBaby sweetyBaby - 8 days ago 6
Scala Question

Implicit Classes in Scala

Below is the example program for Scala Implicit Class:

object Run {
implicit class IntTimes(x: Int) {
def times [A](f: =>A): Unit = {
def loop(current: Int): Unit =

if(current > 0){
f
loop(current - 1)
}
loop(x)
}
}
}


There is an other class that calls "
4 times println("hello")
" as following, but I can not understand "
4 times println("hello")
" mean?

object Demo {
def main(args: Array[String]) {
4 times println("hello")
}
}

Answer

4 times println("hello") roughly translates into:

val c = new IntTimes(4)
c.times(println("hello"))

That is, since there is an implicit class that takes an Int as its only argument, with a method times, doing 4.times implicitly instantiates the class with 4 as argument, and then invokes times on it.