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!*Written by Ben Burton
Related protips
5 Responses
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 + "*"
}Thanks eranation, that's much cleaner!
Short, sweet & concise
simple concise and understandable
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?