了解为什么“拉皮条我的图书馆"在 Scala 中是这样定义的 [英] Understanding why "pimp my library" was defined that way in Scala

查看:36
本文介绍了了解为什么“拉皮条我的图书馆"在 Scala 中是这样定义的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想在 Scala 中给一个类添加一个方法,我需要做一些类似的事情:

If I want to add a method to a class in Scala, I need to do something like:

class RichFoo(f: Foo) {
  def newMethod = f.bar()
}
object RichFoo {
  implicit def foo2Rich(f: Foo) = new RichFoo(f)
}

然后 f.newMethod 将导致创建 RichFoo 实例并调用其方法.

Then f.newMethod will result in creation of RichFoo instance and call its method.

我试图理解为什么它的定义与 Ruby 不同:

I'm trying to understand why it was not defined similarly to Ruby:

override class Foo {
  def newMethod = bar
}

编译器可以查看这个定义,并创建一个带有静态方法 newMethod 的 FooOverride 类,该类获取 Foo 类型的参数并调用其 bar 方法.这就是 Scala 实现 trait 的方式.我仍然需要导入包含 Foo 覆盖的包才能使用它.

The compiler can look at this definition, and create a FooOverride class with static method newMethod that gets a parameter of type Foo and calls its bar method. This is how Scala implements traits. I still need to import the package containing the Foo override to use it.

它似乎涉及较少的打字,不需要我发明名称,并且具有更好的性能(不调用方法和创建对象).隐式转换方法所做的任何事情都可以在附加方法中完成.

It seems to involve less typing, doesn't require me to invent names, and has better performance (not calling a method and creating an object). Anything the implicit conversion method does can be done inside the additional method.

我确定我错过了一些东西,并想深入了解什么.

I'm sure I've missed something and would like to get an insight into what.

推荐答案

除了pimp my library"这个习语之外,隐式转换还有其他用途,所以这并不是他们为什么不这样做"的真正情况相反?",但是他们为什么不这样做呢?".当然,我看不出为什么不能按照您的建议添加扩展方法语法,而且它可能会更简洁一些,但是鉴于该语言已经支持一种实现相同效果的方式,因此对它的需求并不大.

There are other uses for implicit conversions other than just the "pimp my library" idiom, so it's not really a case of "why didn't they do this instead?", but "why didn't they do this as well?". Certainly, I can see no reason why an extension methods syntax couldn't be added as you suggest, and it would probably be somewhat cleaner, but there's not much pressing need for it given that the language already supports a way of achieving the same effect.

2011 年 10 月更新:

有一个为这个用例添加语法糖的新提议:http://scala.github.com/sips/pending/implicit-classes.html

There's a new proposal to add syntax sugar for this use case: http://scala.github.com/sips/pending/implicit-classes.html

这篇关于了解为什么“拉皮条我的图书馆"在 Scala 中是这样定义的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆