Scala/Mill: Step 3, Adding Multiple Dependencies

In the next step with the Scala Mill build tool we’ll add multiple dependencies to a Mill project. The dependencies will be both Scala and Java libraries.

Adding managed dependencies to Mill

Here’s the syntax for how to add multiple dependencies to your Mill build.sc configuration file:

object RssAtomReader extends ScalaModule {

    def scalaVersion = "2.12.11"

    // use `::` for scala deps, `:` for java deps
    def ivyDeps = Agg(
        ivy"org.scala-lang.modules::scala-xml:1.0.6",
        ivy"org.scalaj::scalaj-http:2.3.0",
        ivy"com.rometools:rome:1.8.1",
        ivy"org.jsoup:jsoup:1.11.2",
        ivy"com.typesafe:config:1.4.0",
        ivy"org.slf4j:slf4j-api:1.7.5",
        ivy"org.slf4j:slf4j-simple:1.7.5"
    )

}

As shown in the comments:

  • Use :: to separate the first two fields of Scala dependencies
  • Use : to separate the first two fields of Java dependencies

Adding unmanaged dependencies (plain old Jar files)

You can also manually add one or more jar files to your project. To do so:

  1. Create a lib folder under your project directory, at the same level as your src directory.
  2. Put the jar files in that directory.
  3. Add the code shown below to your build.sc file:
import mill._, scalalib._

object HelloWorld extends ScalaModule {
    def scalaVersion = "2.12.11"
    
    // ADD THIS CODE:
    // see https://www.lihaoyi.com/mill/page/configuring-mill.html#unmanaged-jars
    def unmanagedClasspath = T {
        if (!os.exists(millSourcePath / "lib")) Agg()
        else Agg.from(os.list(millSourcePath / "lib").map(PathRef(_)))
    }
}

Full disclosure: I don’t understand all of that code yet, but I can confirm that it works.

For example, I’m working working on a project that I named HelloWorld, and this is what its directory structure looks like after I created a new lib folder and added a jar file to it:

$ tree .
.
├── HelloWorld
│   ├── lib
│   │   └── stringutils_2.12-1.0.jar
│   └── src
│       └── main
│           └── scala
│               └── hello
│                   └── Hello.scala
├── build.sc

After adding this code to the build.sc file, use that library in your project as needed, then run these commands and your project should compile and run properly:

mill clean
mill HelloWorld

Note that because of the approach taken in the build.sc file, it isn’t necessary to name the directory lib, but I use that name because I’m used to it.

books by alvin