Building multiple Scala modules from SBT

Rishav Sarkar
2 min readSep 9, 2022

--

Suppose we have Scala project with multiple Scala sub projects or multiple Scala modules. These modules need to create seperate jars and the modules can depend on each other. We need to write the build.sbt to package all the sub projects to jars and also create a fat jar for the Scala project.

Below is an example of build.sbt with many sub-projects:

lazy val commonSettings = Seq(
name := "multi-module-scala-project",
version := "1.0.0",
scalaVersion := "2.12.4",
resolvers ++= Seq(
"Local Maven Repository" at "file://" + Path.userHome.absolutePath + "/.m2/repository",
Resolver.sonatypeRepo("releases"),
Resolver.sonatypeRepo("snapshots")
)
)
// PROJECTSlazy val global = project
.in(file("."))
.settings(commonSettings)
// .disablePlugins(AssemblyPlugin) // enabling this statement will skip creating fat jar for the project.
.aggregate(
multi1,
multi2,
lib
)
lazy val multi1 = (project in file("multi1"))
.settings(
name := "multi1",
commonSettings,
assemblySettings,
commonDependencies,
).dependsOn(client)
lazy val multi2 = (project in file("multi2"))
.settings(
name := "multi2",
commonSettings,
assemblySettings,
commonDependencies)
lazy val lib = (project in file("lib"))
.settings(
name := "lib",
commonSettings,
assemblySettings,
commonDependencies)
lazy val assemblySettings = Seq(
assembly / assemblyMergeStrategy := {
case PathList("META-INF","services", xg @ _*) => MergeStrategy.concat
case PathList("META-INF", xs@_*) => MergeStrategy.discard
case x => MergeStrategy.first
}
)
lazy val commonDependencies = {
libraryDependencies ++= Seq(
"org.scalatest" %% "scalatest" % "3.2.12" % Test
)
}

Project Structure for many sub-projects:

/build.sbt
/project/build.properties
/project/target

/target

/multi1/src/main/scala/...
/multi1/src/main/resources/...
/multi1/src/test/scala/...
/multi1/src/test/resources/...

/multi1/target/...

/multi2/src/main/scala/...
/multi2/src/test/scala/...

/multi2/target/...

/lib/src/main/scala/...
/lib/src/main/java/...
/lib/src/test/scala/...

/lib/target/...

Note: The java files must be in src->main->java inside the sub-projects. The java files are compiled together with scala in the same jar.

--

--