This examples shows how to cross-build a project consisting of multiple sub-projects where the sub-projects of different Scala versions depend on a parent project. Also, it attempts to answer StackOverflow question How to make different subclass for each scala version?
Given scala-parent
project, and scala-2.11
and scala-2.12
sub-projects that dependsOn
scala-parent
, then
set crossScalaVersions
on scala-parent
, whilst setting scalaVersion
on sub-projects like so
lazy val scalaParent = (project in file("scala-parent")).settings(crossScalaVersions := Seq("2.11.0", "2.12.0"))
lazy val scala211 = (project in file("scala-2.11")).dependsOn(scalaParent).settings(scalaVersion := "2.11.0")
lazy val scala212 = (project in file("scala-2.12")).dependsOn(scalaParent).settings(scalaVersion := "2.12.0")
Also set crossScalaVersions := Seq()
on the root
project that aggregates other projects:
lazy val root = (project in file("."))
.aggregate(scalaParent, scala211, scala212)
.settings(
name := "sbt-cross-build-dependson-example",
libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.5" % Test,
crossScalaVersions := Seq() // https://github.com/sbt/sbt/issues/4262#issuecomment-405607763
)
Now executing sbt +compile
should correctly cross-build the project:
sbt:sbt-cross-build-dependson-example> +compile
[info] Setting Scala version to 2.12.0 on 2 projects.
...
[info] Updating scala212...
[info] Compiling 1 Scala source to /Users/mario/IdeaProjects/sbt-cross-build-dependson-example/scala-parent/target/scala-2.12/classes ...
[info] Compiling 1 Scala source to /Users/mario/IdeaProjects/sbt-cross-build-dependson-example/scala-2.12/target/scala-2.12/classes ...
...
[info] Setting Scala version to 2.11.0 on 2 projects.
...
[info] Updating scala211...
[info] Compiling 1 Scala source to /Users/mario/IdeaProjects/sbt-cross-build-dependson-example/scala-parent/target/scala-2.11/classes ...
[info] Compiling 1 Scala source to /Users/mario/IdeaProjects/sbt-cross-build-dependson-example/scala-2.11/target/scala-2.11/classes ...
Note how scala-parent
has been cross-compiled for 2.11 and 2.12
> tree -d -L 1 scala-parent/target/
scala-parent/target/
├── scala-2.11
├── scala-2.12
whilst sub-projects were build just for their respective versions
> tree -d -L 1 scala-2.11/target/
scala-2.11/target/
├── scala-2.11
> tree -d -L 1 scala-2.12/target/
scala-2.12/target/
├── scala-2.12