Blog Posts

The new Slick 2.0 database library comes with a simple code generator that generates Scala code for all your tables so you can quickly start coding against your database. It takes into consideration not only the tables and columns, but also primary … Continue reading

playing with scala reflection
06.08.2013 19:58 by

scala is an object-functional programming language, designed to concisely express solutions in an elegant, type-safe and lightweigt manner. scala compiles to java bytecode, so its code runs glueless on the JVM and java libraries can be freely called from scala and vice-versa.

i started using scala about 2 months ago and i’m still impressed so far. simple functionality can be written in a very clean and elegant way and thanks to popular frameworks like play! or lift, the language comes with ‘batteries included’ for web development.

in scala 2.10 the new reflection API was introduced. this API provides the program the ability to inspect and possibly even modify itself at runtime. 

so, let’s see what we can do with it. first of all the API has to be included:

objects and classes can now be instantiated at runtime using an appropriate runtime mirror. by obtaining a mirror from the current classloader, all types and classes are available. invoking the instance of classes and objects differs a little bit, since objects in scala are treated like singleton objects.

so, assuming you already have an object like this:

you can now invoke a method of this object at runtime:

of course, this is just a small example of the power of scala’s new reflection API. it provides a possibility for programs to modify themselves at compile time, and this is done in a very clean and elegant way. this enables a new form of “metaprogramming” in scala. further readings can be found at the official scala docs.