Since scala.runtime.RichString is declared as final, you can't extend it like class MyString extends RichString
. I'd like to 'pimp the library' and simply add another method. How would I do this?
Since a key rule of implicits is that only one is ever applied to make a given (sub-)expression type-check, pimping RichString
in order to add in turn to the complement of methods it adds to String
will not allow you to see the methods of your RicherString
(if you will) class as if they were available directly on String instances. They would be available if you had a RichString
, of course, and RichString
instances are trivially available from String
instances by simple type ascription. But still, it's not what anyone would call convenient.
So for practical purposes, what you're asking for isn't really possible in Scala.
On the other hand, if you just need alternate augmentation of String
, you can just define your own augmented string class. If there's no overlap between the methods it defines and those defined in RichString, there will never be any ambiguity for the compiler to resolve in deciding which to apply. That's probably good enough, right?
Additionally, this approach (an alternate, non-overlapping implicit conversion) won't break when you switch to Scala 2.8, which has StringOps
in place of RichString
.
To do this, you would do something similar to the following:
class MyRichString(underlying:String){
def myNewMethod = { ... }
}
implicit def addMyMethods(s:String)=new MyRichString(s)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With