Tag Archives: underscore.js

How Scala implicits provide underscore.js / jQuery-style augmentations

Scala implicits allow one to write libraries like jQuery or underscore.js that add methods to existing classes without the syntactic overhead. This is very quick to demonstrate.

Consider the useful pluck method that underscore.js adds to Javascript arrays, used like so:

> _([{foo: 'baz'}, {foo: 'bizzle'}]).pluck("foo")
["baz", "bizzle"]

The underscore function sort of lets us “pretend” that pluck is a method of arrays of objects. Here is a similar method addition in Scala using implicits.

object Pluck {
  implicit def withPluck[T](ms: Seq[Map[String, T]]) = new {
    def	pluck(field: String) = ms.map(_.get(field))

And here’s how you use it:

$ sbt console
scala> import Pluck._
scala> Seq(Map("foo" -> "baz"), Map("foo" -> "bizzle")) .pluck("foo")
res0: Seq[Option[java.lang.String]] = List(Some(baz), Some(bizzle))

In Scala, you can trivially “add” a method to an existing class without modifying that class or adding syntactic overhead. One may debate whether this is a good idea to do very often, of course, but clearly underscore.js is simply adding methods one really would expect an array to have.

Tagged , ,