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?
This would be the code after Daniel's comment.
Since version 2.10 of Scala, it is possible to make an entire class eligible for implicit conversion
In addition, it is possible to avoid creating an instance of the extension type by having it extend AnyVal
For more information on implicit classes and AnyVal, limitations and quirks, consult the official documentation:
The Pimp My Library pattern is the analogous construction:
Per @Daniel Spiewak's comments, this will avoid reflection on method invocation, aiding performance:
In Scala we use the so-called (by the inventor of the language) Pimp My Library pattern, which is much discussed and pretty easy to find on the Web, if you use a string (not keyword) search.