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!

2 Comments »

  1. The thing I really like about that feature, is unlike in Ruby and similar dynamic languages, it’s not really monkey patching. The implicit conversion will only happen when you explicitly include the implicit conversion in scope, by either declaring it or importing it, so the magic sauce is not hidden from you and you can decide not to use it.

    Comment by Chris — May 12, 2011 @ 2:55 pm | Reply

    • That’s a great point, I agree. When I first used Implicit Conversions, it made me feel more at ease being able to explicitly include the implicit conversion in the code where I wanted it to apply, knowing it would only be available within that scope. Also I think this makes it easier for the next developer seeing your code for the first time to understand where the magic is happening. Thanks for mentioning that excellent point Chris!

      Comment by Brian — May 12, 2011 @ 8:31 pm | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: