Implicit classes in Scala are an underused and oft misused feature. I don’t feel that they are explained very well and have a bit too much mystery for the beginner to grasp. I was playing around and thought it might help to show the explicit syntax, to more easily explain the “magic” to someone.

In a nutshell:

import scala.language.postfixOps

object Factorial {

implicit class IntDecorator(val n: Int) {
def ! = 1 to n product
}

def factorial(n: Int) = n! // implicit

def factorial2(n: Int) = IntDecorator(n).! // explicit

}