18.16. Using Build.scala Instead of build.sbt

Problem

You want to use the project/Build.scala file instead of build.sbt to define your Scala project, or you need some examples of how to use Build.scala to solve build problems that can’t be handled in build.sbt.

Solution

The recommended approach when using SBT is to define all your simple settings (key/value pairs) in the build.sbt file, and handle all other work, such as build logic, in the project/Build.scala file. However, it can be useful to use only the project/Build.scala file to learn more about how it works.

To demonstrate this, don’t create a build.sbt file in your project, and then do create a Build.scala file in the project subdirectory by extending the SBT Build object:

import sbt._
import Keys._

object ExampleBuild extends Build {

  val dependencies = Seq(
    "org.scalatest" %% "scalatest" % "1.9.1" % "test"
  )

  lazy val exampleProject = Project("SbtExample", file(".")) settings(
    version       := "0.2",
    scalaVersion  := "2.10.0",
    scalacOptions := Seq("-deprecation"),
    libraryDependencies ++= dependencies
  )

}

With just this Build.scala file, you can now run all the usual SBT commands in your project, including compile, run, package, and so on.

Discussion

The Build.scala file shown in the Solution is equivalent to the following build.sbt file:

name := "SbtExample"

version := "0.2"

scalaVersion := "2.10.0"

scalacOptions += "-deprecation"

libraryDependencies += "org.scalatest" %% "scalatest" % "1.9.1" % "test"

As mentioned, the recommended approach ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.