Wednesday, March 12, 2008

Update: Inter-type declarations with implicit conversions

With some closure magic it's possible to shorten the code to build a class extension aka. to add some inter type members.
class ClassExtension[S, T](createExtendedObject: => T) {

val extendedObjects = new HashMap[S, T]

implicit def extendObject(o : S) : T = {
if (!extendedObjects.contains(o)) {
extendedObjects += o -> createExtendedObject;
}
extendedObjects(o);
}
}

Instead of making the class abstract and using a factory method on the concrete class, we can use a closure for the construction of the extended / alternative object.

The class can be used like this:
def main(args : Array[String]) : Unit = {
object PositionVertexExtension extends ClassExtension[Vertex, Position](new Position);
import PositionVertexExtension._;
val v = new Vertex("v1");
v.x = 2.3;
println(v.x)
}

This code shows another nice feature of scala. It is possible to have imports scoped to blocks. So in this case the extension is only visible in this local context. This is comparable to Groovy where categories are applied by the use controll structure.

No comments: