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)
}
Since version 2.10 of Scala, it is possible to make an entire class eligible for implicit conversion
implicit class RichInt(i: Int) {
def square = i * i
}
In addition, it is possible to avoid creating an instance of the extension type by having it extend AnyVal
implicit class RichInt(val i: Int) extends AnyVal {
def square = i * i
}
For more information on implicit classes and AnyVal, limitations and quirks, consult the official documentation:
- http://docs.scala-lang.org/overviews/core/implicit-classes.html
- http://docs.scala-lang.org/overviews/core/value-classes.html