Tag Archives: java

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.

Stephan Schmidt has a blog entry on how explicit static type declarations are for the benefit of the developer, and not the compiler. That is, when you have something like this:

Person person = mysteriousCall()

you know at a glance that the object reference person is in fact of type Person. To a compiler, this might be obvious through type inference - in this case, by looking at the return type of the mysteriousCall function.

In Java, you always declare the member types explicitly, but for a statically typed language that does rely on type inference (I’m thinking Scala), the type declaration Person is clearly redundant. And if there’s one thing any programmer hates, it’s redundancy. So, one could just go with

val person = mysteriousCall()

and be done with it: the compiler will infer the type. Now, Schmidt makes a good point in that now the type of person is not immediately obvious to the naked eye, since there’s no explicit declaration in sight. This gave me an idea, which I posted as a comment to the blog entry:

What if a smart IDE could consult the compiler and decorate / annotate the above code line visually by showing the type of the person field? Now, the type would be explicitly shown to the user, but information that’s available through type inference wouldn’t have to be duplicated in the actual code.

Something like

val person : Person = mysteriousCall()

where : Person is the visual aid shown by the IDE, in standard Scala type declaration notation. Now, the type of the value is clearly visible, but there are no redundant type declarations in the code.

I wonder if anyone’s thought of this before (likely), and whether some tool already implements this for some language with type inference (less likely)?