Scala equivalent of C#’s extension methods?

The Pimp My Library pattern is the analogous construction:

object MyExtensions {
  implicit def richInt(i: Int) = new {
    def square = i * i
  }
}


object App extends Application {
  import MyExtensions._

  val two = 2
  println("The square of 2 is " + two.square)

}

Per @Daniel Spiewak’s comments, this will avoid reflection on method invocation, aiding performance:

object MyExtensions {
  class RichInt(i: Int) {
    def square = i * i
  }
  implicit def richInt(i: Int) = new RichInt(i)
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)