My Adventures in Coding

April 19, 2011

Scala – Extending a built in class with Implicit Conversions

Filed under: Scala — Brian @ 11:00 pm
Tags: ,

The String class in Scala has a “replaceFirst” method, but what if you really want it to have a “replaceLast” method as well in your code. One way to accomplish this task would be:

class StringHelper(str: String) {
  def replaceLast(regex: String, replacement: String) = str.reverse.replaceFirst(regex, replacement.reverse).reverse
}

val myString = new StringHelper("Hello:")
println(myString.replaceLast(":",""))

Now that looks kind of ugly, having to directly use our StringHelper in the code. Fortunately Scala’s Implicit Conversions allows you to keep the code clean and let Scala do the work for you. All we have to do is create an implicit wrapper for StringHelper:

class StringHelper(str: String) {
  def replaceLast(regex: String, replacement: String) = str.reverse.replaceFirst(regex, replacement.reverse).reverse
}

implicit def stringWrapper(string: String) = new StringHelper(string)

val myString = "Hello:"
println(myString.replaceLast(":",""))

So now whenever the method “replaceLast” is called on a String, Scala is smart enough to do the implicit conversion of the String to StringHelper for me automatically. Scala Implicit Conversions allows me to add additional functionality to an existing built in library class, without having to clutter my code with references to messy wrapper classes.

That’s all!

Create a free website or blog at WordPress.com.