Last Updated: July 25, 2016
·
28.42K
· benburton

Scala's "Pimp My Library" Pattern example

I always find myself wanting to find a quick example of this to show people. Essentially, the "Pimp My Library" pattern allows you to decorate classes with additional methods and properties. The following is how you would add a method "bling" to java.lang.String which will add asterisks to either end:

class BlingString(string: String) {
    def bling = "*" + string + "*"
}

implicit def blingYoString(string: String) = new BlingString(string)

This defines a class BlingString with the bling method, and then uses an implicit definition to "teach" Scala how to convert from a java.lang.String to the new type. You can then call the method on any java.lang.String object, as long as the implicit is defined in the same scope:

scala> "Let's get blinged out!".bling
res0: java.lang.String = *Let's get blinged out!*

5 Responses
Add your response

I came here courtesy of google, looking for what pimping means in the Scalasphere, thanks! Well, with power comes some responsibility..... but isn't there a syntactically simpler way to add behavior to a type? this is soooo cumbersome and blingYoString is a name you'd never use in your code again, so it feels like it should have rather been anonymous. What do you think?

over 1 year ago ·

Recommended syntax for this is to use an implicit value class to avoid runtime creation of a wrapper class: http://docs.scala-lang.org/overviews/core/value-classes.html

implicit class BlingString(string: String) extends AnyVal {
    def bling = "*" + string + "*"
}
over 1 year ago ·

Thanks eranation, that's much cleaner!

over 1 year ago ·

Short, sweet & concise

over 1 year ago ·

simple concise and understandable

over 1 year ago ·