Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding why "pimp my library" was defined that way in Scala

Tags:

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)
}

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

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

override class Foo {
  def newMethod = bar
}

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.

like image 753
IttayD Avatar asked Dec 16 '09 10:12

IttayD


1 Answers

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.

Update October 2011:

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

like image 63
Matt R Avatar answered Oct 16 '22 23:10

Matt R