Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional compilation in Scala

Tags:

scala

sbt

I am working on a library which depends on Scala 2.9 but only for a minor feature. I would like to propose version compatible with 2.8, but I don't want to maintain two code branch. Since I'm using SBT, I would like to benefits from it cross-compilation features.

However I don't know is there is a way to provide an equivalent of conditional compilation, to include a piece of code only if Scala 2.9 is used. Reflexivity could be an option (but how?).

Edit: The features I am using in 2.9 are the new sys package object.

like image 319
paradigmatic Avatar asked Jul 05 '11 08:07

paradigmatic


2 Answers

I got it with reflection. So if I want to get the sys.SystemProperties, I can do:

try {
    val k = java.lang.Class.forName("scala.sys.package$")
    val m = k.getMethod( "props" )
    // etc.
} catch {
    case _ => throw new UnsupportedOperationException("Only available with Scala 2.9")
}

But it is so boring and ugly that I think I will drop those features...

like image 153
paradigmatic Avatar answered Sep 22 '22 13:09

paradigmatic


Read this blog post, which describes how to do it with metaprogramming:

http://michid.wordpress.com/2008/10/29/meta-programming-with-scala-conditional-compilation-and-loop-unrolling/

like image 32
Jean-Philippe Pellet Avatar answered Sep 19 '22 13:09

Jean-Philippe Pellet