Pacific-Design.com

    
Home Index

1. Scala

2. Implicit Class

Scala / Implicit Class /

Implicit Class

To create an implicit class, simply place the implicit keyword in front of an appropriate class.

1. Implicit Class must be defined inside of another trait/class/object.
2. Implicit Class may only take one non-implicit argument in their constructor.

    object Helpers {
      implicit class IntWithTimes(x: Int) {
        def times[A](f: => A): Unit = {
          def loop(current: Int): Unit =
            if(current > 0) {
              f
              loop(current - 1)
            }
          loop(x)
        }
      }
    }

    scala> import Helpers._
    scala> 2 times println("Kevin")
    Kevin
    Kevin

Reference:

http://docs.scala-lang.org/overviews/core/implicit-classes.html