Scala Goodness: RichString

Scala is a marvelous beast. Fire up the Scala shell and enter:

scala> "capitalize"
res0: java.lang.String = capitalize

scala> "capitalize".capitalize
res1: String = Capitalize

How can that be? "capitalize" is of type java.lang.String, and the Java class does not have a capitalize method. But the Scala RichString methods has (Scala 2.8 will use StringOps). And there are more methods to RichString, like reverse, drop, toDouble, toInt and toLong

scala> "123".toInt
res2: Int = 123

scala> "123".toLong
res3: Long = 123

Another nice one, is format. Not as nice as as GStrings in Groovy, but nevertheless:

scala> "hello %s".format("stephan")
res6: String = hello stephan

How can Scala do this? There is a conversion going on in Scala, which automatically converts your Java String to RichString when the method cannot be found in String but in RichString. The relevant code is in Predef (look for yourself and see how deep the rabbit-hole goes):

implicit def stringWrapper(x: String) = new runtime.RichString(x)

Scala Glory!