Tag Archives: bdd

I’ve been delving into Scala quite a bit the last couple of weeks. Coderspiel has a piece on one of the coolest features in Scala: implicit type conversions.

In theory, these conversions allow you to use an object of type X in an expression where an object of type Y is expected. To achieve this, you define an implicit conversion function that takes an X and returns a Y (f: X -> Y for the mathematically inclined), and tag it with the language keyword implicit. Now, Scala can implicitly (and transparently to you, the coder) convert X’s to Y’s, if needed. Consider an example:

class Apple

class Orange {
  def hi = Console.println("Hi, orange!")
}

object ApplesToOranges extends Application {
  // This is our type conversion function.
  // Note that its name can be ANYTHING:
  //   only the type signature matters!
  implicit def applesToOranges(a: Apple) : Orange = new Orange

  val a = new Apple()

  // the implicit conversion occurs here, as Apple
  // doesn't have a method called "hi", but Orange
  // does, and we have defined the implicit conversion
  // from Apples to Oranges
  a.hi
}

This example doesn’t make much sense, but shows you the mechanics of implicit conversions. In practice, implicit conversions allow you to do some seriously cool things, such as extending existing Java class libraries (check out the Coderspiel entry for the JDBC and Wicket examples) elegantly.

There’s more to implicit type conversions than merely forcing legacy code to behave, though. For example, now that we can convert objects between different types pretty much arbitrarily and transparently, some DSL-like constructs become easier. Consider the RSpec -style assertions found in many BDD frameworks:

product.price.should == 5
character.name.should == "Mudkip"

Now, these clearly boil down to the format of

(some expression) should (expectation)

Perhaps we could represent these expectations using a class called Expectation, and have it evaluate any conditions thrown at it. Since we want to be able to say should for any object whatsoever, we need an implicit conversion from any type to an Expectation. Drum roll, please:

case class Thing(name: String)

object Expectations extends Application with Specification {
  val mudkip = new Thing("mudkip")
  mudkip.name should equal("mudkip")

  (2 * 3) should equal(6)

  // BOOM: failure!
  false should equal(true)
}

// quick and dirty implementation
// just to illustrate the mechanics

class Expectation[T](value: T) {
  def should(eq: Equality[T]) = {
    if(value != eq.value) {
      throw new AssertionError(
        "Expected " + eq.value + " but was " + value
      )
    }
  }
}

case class Equality[T](value: T)

trait Specification {
  implicit def anythingToExpectation[T](value: T)
    = new Expectation[T](value)

  def equal[T](t: T) = new Equality[T](t)
}

Specs, a BDD framework for Scala, seems to utilize implicit conversions in this manner to support a pretty concise way of writing specifications.

So, in inaccurate yet nerd-appealing terms, implicit type conversions are sort of like having the power of Ruby’s open classes in a statically typed language - monkey patching, wicked! Don’t over-use ‘em, though: you might hit issues such as ambiguity between different conversions (though the conversion functions are scoped.) As open classes, they seem like a prime candidate for the “I don’t know what I’m doing but if I stick this here, it seems to work” -type of coding.

Btw, the PDF version of the forthcoming book on Scala, aptly named Programming in Scala, is available through Artima’s early access program.