Thursday 14 April 2011

Playing with Scala Dynamic

The news spread fast through twitter when the Scala dynamic trait was checked into the Scala repository some months ago. It's now in the 2.9RC1 version that arrived just the other day. So I wondered about what to use something like that for. It was intended for inline communication with dynamic languages like Ruby and Python, but I decided to try to mimic Ruby-on-Rails table inheritance.

For this I needed Scala 2.9RC1 (http://www.scala-lang.org/downloads) and apparently the '-Xexperimental' command line argument. My scala command line for experimenting look like this:

# scala-2.9.0.RC1/bin/scala -Xexperimental -classpath ~/.ivy2/cache/com.h2d/h2/jars/h2-1.2.138.jar

For simplicity I used a h2-database and set it up like this:



Then of course we have my Dynamic trait which implement the 'applyDynamic(...)(...)' method. This is similar to Rubys missing method; it simply looks through the map of data that it got to see if the method you called exist. So far only data access is supported:



Of course we need to have a companion object to do the data retrieval. It will only support one method 'findAll':



Then we can go on to create the important classes to represent the table:



So then will this fly? If so I should be allowed to access the data through methods I haven't written:



Some thoughts:

Constantly having to cast return values destroys some of the fun. Also, I dislike the idea of these fields spreading the dynamic plague all over my code. An even more unsettling thought is what this does to the line between static goodness and dynamic ficklety. We know when we see a text in "quotes" that this is where the compiler draw the line and takes no responsibility. With the dynamic trait however we don't know whether 'obj.NAME' really exists. I guess this is a little like sex ed in school; now that you know how it's done. Don't do it ;-)