开发者

Is there a way to extend Scala's RichString?

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜