Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are SBT projects declared as lazy vals?

Tags:

sbt

Per the SBT documentation, "A project is defined by declaring a lazy val of type Project."

That is certainly the norm, and is what we are doing, but I was wondering what if any is the reason it needs to be lazy.

Using a regular val instead of lazy val seems to work. Of course using strict vals results in the project definitions being initialized in order, which means forward references don't work, requiring projects to be defined in dependency order.

For a relatively large build, with 53 interdependent projects, having ordering enforced is actually a Good Thing™, so I was wondering if there's an actual reason for using lazy val -- besides allowing definitions to occur in arbitrary order.

like image 625
aij Avatar asked Oct 04 '17 15:10

aij


1 Answers

This is a common "best practice". I haven't seen anybody explicitly state this, but from my experience this practice is related to a few features of sbt.

  1. sbt parses any *.sbt file
  2. sbt evaluates an *.sbt file top to bottom
  3. you can created dependencies between everything in multiple sbt files

Now imagine you want to structure your build.sbt for readability. We have some common settings and 3 projects (a root and two builds)

val root = project.in(file("."))
      .settings(commonSettings)
      .aggregate(api, server)

val api = project.in(file("api"))
      .settings(commonSettings)
      .settings(name := "server")

val server= project.in(file("api"))
      .settings(commonSettings)
      .settings(name := "api")
      .dependsOn(api)

val commonSettings = Seq(organization := "com.example")

sbt won't start as multiple things are wrong in this build.sbt

  1. The api and server module are referenced in the root project before they are defined
  2. commonSettings is referenced before its definition in all projects

Without making everything lazy it gets hard to refactor your build files. This is the reasons all sbt documentation uses lazy vals every. To avoid confusion and frustration for first time users.

hope that helps, Muki

like image 130
Muki Avatar answered Oct 16 '22 17:10

Muki