Pimp my library

The name of this pattern comes from Martin Odersky’s article.

To illustrate, here’s an example from the mailing list. The goal is to add a headOr method to the standard library List class, without modifying the Scala distribution:

We define a class which wraps List and provides the desired functionality:

class ListExtensions[A](xs : List[A]) {
    def headOr(f : => A) : A = xs match {
        case h :: _ => h
        case Nil    => f
    }
}

Then we define an implicit conversion to construct the wrapper class when necessary:

implicit def listExtensions[A](xs : List[A]) = new ListExtensions(xs)

Whenever the compiler encounters a call to a method that doesn’t exist in the target class, it searches through the list of implicit conversions for an alternative class which does provide the required method, and inserts a call to the conversion function. So now these work:

println(List(1,2,3).headOr(0))     ==> 1
println(Nil.headOr(0))             ==> 0

Note that it is not possible to put defs at the top level, so you can’t define an implicit conversion with global scope. The solution is to place the def inside an object, and then import it, i.e.

object Implicits {
    implicit def listExtensions[A](xs : List[A]) = new ListExtensions(xs)
}

And then at the top of each source file, along with your other imports:

import Implicits._
 
patterns/pimp-my-library.txt · Last modified: 2007/05/17 19:31 by jwebb
 
Recent changes RSS feed Valid XHTML 1.0 Driven by DokuWiki