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.