Cross-compile Multiple Versions of Scala via SBT
To start supporting multiple versions of Scala within a project you need to cross compile your sources for the various supported Scala versions.
You can achieve that with the crossScalaVersions directive within your SBT build file specifying all the Scala versions you want to support:
:= Seq("2.11.8", "2.12.2") crossScalaVersions
But how do you go about supporting APIs that exist in one version but not the other version of Scala within the same project?
Since SBT 0.13.8 (thanks to this PR) you can simply separate your src directories to versioned equivalents and have everything just work as expected.
For example to support custom code for Scala 2.11 and 2.12, you’d create the following directories:
- src/{main,test}/scala-2.11 //for 2.11 specific changes
- src/{main,test}/scala-2.12 //for 2.12 specific changes
The default src/{main,test}/scala directory will be used for common changes.
When compiling your project simply use the + directive before a task to denote cross building the project across all Scala versions for that task. For example to run tests across all versions use:
+ test
To switch to a specific Scala version use ++. For example to switch to Scala 2.12 use:
++ 2.12
When compiling source for the different Scala versions, they will be written out to the respective target directories:
- target/scala-2.11 //for 2.11 classes
- target/scala-2.12 //for 2.12 classes
For more information read the SBT documentation on cross building.