the blog for developers

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!

About the author

stephan Stephan Schmidt has been working with internet technologies for the last 20 years. He was head of development, consultant and CTO and is a speaker, author and blog writer. He specializes in organizing and optimizing software development helping companies by increasing productivity with lean software development and agile methodologies. Want to know more? All views are only his own. You can find him on Google +

Discuss on Hacker News Vote on HN