k_1jzw
Last Updated: July 25, 2016
·
16.97K
· benburton
Fe981ba1d30b3b54836d158ce528416c

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!*
Say Thanks
Respond

5 Responses
Add your response

11013
Identicon

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 ·
11447

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 ·
12605
Fe981ba1d30b3b54836d158ce528416c

Thanks eranation, that's much cleaner!

over 1 year ago ·
27751
Kayvan

Short, sweet & concise

over 1 year ago ·
27914

simple concise and understandable

11 months ago ·