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 中是什么样子?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Pimp My Library 模式是类似的结构:
Per @Daniel Spiewak 的评论,这将避免方法调用的反射,从而提高性能:
The Pimp My Library pattern is the analogous construction:
Per @Daniel Spiewak's comments, this will avoid reflection on method invocation, aiding performance:
从 Scala 2.10 版开始,可以使整个类符合隐式转换的条件。
此外,可以通过扩展 AnyVal 来避免创建扩展类型的实例。
有关隐式类和 AnyVal、限制和怪癖的更多信息,查阅官方文档:
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:
这将是 Daniel 的评论之后的代码。
This would be the code after Daniel's comment.
在 Scala 中,我们使用所谓的(由该语言的发明者)Pimp My Library 模式,如果您使用字符串(而不是关键字),该模式已被广泛讨论并且很容易在 Web 上找到搜索。
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.
Scala 3 现在有扩展方法。从功能上看,它与 C# 和 Kotlin 的预期类似。
https://dotty.epfl.ch/docs/reference/contextual/扩展方法.html
https://github.com/scala/scala
https://github.com/lampepfl/dotty
最近(截至本文)拉取显示语法被简化。截至本文为止,稳定版本仍然是 2.x。但是有一个 3.xRC,我注意到 Jetbrains 已经在 Idea 中支持它,部分我认为。
Scala 3 now has extension methods. Functionally it seems similar as expected to C# and Kotlin.
https://dotty.epfl.ch/docs/reference/contextual/extension-methods.html
https://github.com/scala/scala
https://github.com/lampepfl/dotty
A recent (as of this post) pull shows the syntax being simplified. Stable version as of this post is still 2.x. But there is a 3.xRC, and I noticed Jetbrains already supports it in Idea, partially I assume.