Thursday, February 03, 2011

Scala's upcoming dynamic capabilities

I was surprised to see the Scala team check in a new "Dynamic" trait into Scala trunk recently.  Once this trait is mixed in to your class, any unresolved method calls are passed to an invokeDynamic() method, much like Ruby's method_missing.

I've been thinking about this a lot, and I see three decent reasons for the inclusion of the Dynamic trait:
1. Integration with dynamic languages on the JVM.
2. DSLs for accessing data where there's already no type safety, ie JSON and XML (written by @jorgeortiz85, I think)
3. DSL for reflection. Reflection libraries are ridiculously verbose, and like JSON/XML/etc libraries, offer little static typing benefits anyway.

I think #1 is very convincing.  LinkedIn and their LinkedIn Signal is one of the high-profile usages of Scala in industry, and it is a mixed Scala/JRuby project.  And why the heck not?  I'm very much warming to the idea that there is no Next Big Language, and programmers of different mindsets will be able to work together with the best tools possible.

Using the Dynamic trait is very easy, and really fun.  I thought I'd try hooking up Scala to Ruby using Dynamic, JRuby, and the Java Scripting Engine (JSR 223).  I was really pleased with how easy it was.  Here's some Ruby:


With a little setup (installing JRuby to get the "jruby" scripting engine and getting Scala trunk running), I had this simple Scala class:


The Ruby above can be annotated with type information, allowing jrubyc to compile down to normal old class files with complete type information.  In that case, we'd only need Dynamic for sugaring calls to "dynamic finders" which aren't declared in the class at all.  I imagine the situation is similar for other dynamic languages on the JVM.  I have to wonder why dynamic invocation would be preferable to calling static bindings of these dynamic classes.  I would love to learn more about how this will all work out in practice.

I have no information on this whatsoever, but from what I can tell this would be in Scala 2.9, which is slated for release in "weeks not months".

Update 3/28/2011:  For Scala 2.9This method is now called "applyDynamic", but is only available with the -Xexperimental flag.

1 comment:

JP @ java debugging tutorial said...

Scala offering so many good feature but still no major development is captured by scala , Java still is number one, when is Scala going to create its place ?

Thanks
String vs StringBuffer vs StringBuilder in Java