Scala相当于C#的扩展方法吗?

在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()); } }} 

这个简单的扩展方法在Scala中看起来如何?

皮条客我的图书馆模式是类似的结构:

 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的评论,这将避免对方法调用,辅助性能的反思:

 object MyExtensions { class RichInt(i: Int) { def square = i * i } implicit def richInt(i: Int) = new RichInt(i) } 

从Scala 2.10版本开始,可以让整个class级都有资格进行隐式转换

 implicit class RichInt(i: Int) { def square = i * i } 

另外,可以通过扩展AnyVal来避免创build扩展types的实例

 implicit class RichInt(val i: Int) extends AnyVal { def square = i * i } 

有关隐式类和AnyVal的更多信息,限制和怪癖,请参阅官方文档:

这将是丹尼尔评论后的代码。

 object MyExtensions { class RichInt( i: Int ) { def square = i * i } implicit def richInt( i: Int ) = new RichInt( i ) def main( args: Array[String] ) { println("The square of 2 is: " + 2.square ) } } 

在Scala中,我们使用所谓的(由语言的发明者) Pimp My Library模式,如果您使用string(而不是关键字)search,那么在Web上可以很容易地findPimp My Library模式。