sweetyBaby sweetyBaby - 1 year ago 90
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){
loop(current - 1)

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 Source

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

val c = new IntTimes(4)

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download