Scala 相当于 C# 的扩展方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3119580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala equivalent of C#’s extension methods?
提问by John
In C# you can write:
在 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());
}
}}
How would this simple extension methodlook like in Scala?
这个简单的扩展方法在 Scala 中会是什么样子?
回答by Mitch Blevins
The Pimp My Librarypattern 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:
根据@Daniel Spiewak 的评论,这将避免对方法调用的反射,从而提高性能:
object MyExtensions {
class RichInt(i: Int) {
def square = i * i
}
implicit def richInt(i: Int) = new RichInt(i)
}
回答by megri
Since version 2.10 of Scala, it is possible to make an entire class eligible for implicit conversion
从 Scala 2.10 版开始,可以使整个类适合隐式转换
implicit class RichInt(i: Int) {
def square = i * i
}
In addition, it is possible to avoid creating an instance of the extension type by having it extend AnyVal
此外,可以通过扩展 AnyVal 来避免创建扩展类型的实例
implicit class RichInt(val i: Int) extends AnyVal {
def square = i * i
}
For more information on implicit classes and AnyVal, limitations and quirks, consult the official documentation:
有关隐式类和 AnyVal、限制和怪癖的更多信息,请参阅官方文档:
回答by OscarRyz
回答by Randall Schulz
In Scala we use the so-called (by the inventor of the language) Pimp My Librarypattern, which is much discussed and pretty easy to find on the Web, if you use a string (not keyword) search.
在 Scala 中,我们使用所谓的(由该语言的发明者提供)Pimp My Library模式,如果您使用字符串(而非关键字)搜索,该模式被广泛讨论并且在 Web 上很容易找到。

