Last Updated: February 25, 2016
·
12.84K
· joseraya

Extension methods in Scala

The idiomatic way to provide extension methods in Scala is via the "Pimp my library" pattern using implicit conversions. That is, if I want to add a method plus to the Int class all I have to do is define a new type ExtendedInt with this method and provided an implicit conversion so that, whenever the compiler sees an Int but needs an ExtendedInt it will convert it automatically:

class ExtendedInt(value: Int) {
  def plus(other:Int) = value + other
}

implicit def extendInt(i: Int) = new ExtendedInt(i)

Now we can use 1.plus(2) in our code

I found in this stack overflow thread an easier way to do this in scala 2.10.

implicit class ExtendedInt(val value: Int) extends AnyVal {
  def plus(other:Int) = value + other
}

And now we can use 2.plus(2) in our code

The thread also points to this resources for further understanding of the topic: