Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to extend Scala's RichString?

Tags:

string

scala

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?

like image 729
pr1001 Avatar asked Jun 20 '10 23:06

pr1001


1 Answers

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)
like image 172
Randall Schulz Avatar answered Oct 15 '22 04:10

Randall Schulz