Monday, February 8, 2010

Dynamic calls using Structural Types

Using reflection can be a real pain in Java since the API is a Java API and consists of many gets and searches through collections not to mention so many exceptions that need to be handled. In Scala there is a wonderful way to clean up a reflective call down to a single line (assuming you don't want to worry about handling exceptions.) Here structural typing can really be a pleasure.

// I am assigning a string to an Any reference

scala>val s:Any = "hello :D"

s: Any = hello :D

// Any does not have a length method

scala> s.length

< console>:6: error: value length is not a member of Any

s.length

^

/*

But I can cast it to a structural type with a length method

*/

scala> s.asInstanceOf[{def length:Int}].length

res2: Int = 8

There are restrictions to this. For example implicits will not work:

/*

The method r is part of StringLike (or RichString in Scala 2.7)

and there is an implicit conversion from String to RichString/StringLike.

The structural type does not try to apply the implicits because implicits are a

compile time artifact and that information is not kept at run time. Perhaps this

Search This Blog

About Me

Jesse EicharI am a senior software developer at Camptocamp SA (Swiss office) and specialize in open-source geospatial Java projects. I am a member of the uDig steering committee and a contributor to Geotools and Mapfish. In addition I regularly work with Geoserver and Geonetwork.

In my free time I am a Scala enthusiast. I am working on the Scala IO incubator project and WebSpecs a Specs2 based testing framework for webapplications.