In C# è possibile scrivere:Scala equivalente dei metodi di estensione di C#?
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());
}
}}
Come sarebbe questo semplice extension method assomigliare a Scala?
Attenzione: utilizzando il nuovo {...} 'la sintassi, si sta effettivamente facendo il compilatore di dedurre un tipo strutturale per il metodo' richInt' significato ' che ogni invocazione di 'square' sarà fatta usando la reflection (un killer della performance). Sarebbe meglio definire una classe 'RichInt' che definisce' square' e viene restituita dal metodo 'richInt'. –
@Daniel, potresti pubblicare il codice che stai descrivendo? – OscarRyz
@Support Aggiungi 'class RichInt (i: Int) {def square = i * i}' a 'MyExtensions' e fai' new RichInt (i) 'nel metodo' richInt'. –