Scala equivalent of C#’s extension methods?

John picture John · Jun 25, 2010 · Viewed 15.3k times · Source

In C# you can write:

using System.Numerics;
namespace ExtensionTest {
public static class MyExtensions {
    public static BigInteger Square(this BigInteger n) {
        return n * n;
    }
    static void Main(string[] args) {
        BigInteger two = new BigInteger(2);
        System.Console.WriteLine("The square of 2 is " + two.Square());
    }
}}

How would this simple extension method look like in Scala?

Answer

Mitch Blevins picture Mitch Blevins · Jun 25, 2010

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)
}