In Scala 2.9 to add custom methods to a library class (enrich or "pimp" it) I had to write something like this:
object StringPimper {
implicit def pimpString(s: String) = new {
def greet: String = "Hello " + s
}
}
As Scala 2.10 was released, I've read that it introduces implicit class definition which, theoretically, was meant to simplify the above task by removing the need in an implicit method returning an object of an anonymous class. I thought it was going to enable me to write just
implicit class PimpedString(s: String) {
def greet: String = "Hello " + s
}
which looks much prettier for me. But, such a definition causes a compilation error:
`implicit' modifier cannot be used for top-level objects
which is solved by wrapping the code in an object again:
object StringPimper {
implicit class PimpedString(s: String) {
def greet: String = "Hello " + s
}
}
needless to say, this almost neutralizes the sense of the improvement.
So, is there a way to write it shorter? To get rid of the wrapper object?
I actually have a MyApp.pimps package where all the pimps go (I don't have too many, I'd use some separate packages if I had) and I am sick of importing MyApp.pimps.StringPimper._ instead of MyApp.pimps.PimpedString or MyApp.pimps._. Of course I could put all the implicit classes in a single wrapper object, but this would mean to put them all in a single file, which would be pretty long - quite ugly solution.
Well, the compiler error sais it all. You just can't define an implicit class at top-level. That means you either use a wrapper object (which can also be a package object), or define the class directly in the scope were it is meant to be used (in the rare case where it doesn't have to be reusable).
The reason for that is that you wouldn't be able to import the implicit conversion without the wrapper. You can't import the implicit class (precisely: the conversion) by its own name.
Besides that, I would suggest using a slightly different signature (see Value Classes):
which has the effect that the calls to your extension methods can (and will) be inlined.