sbt basics
I’ve been building Scala projects for a while now, but I’ve either been writing basic, single file scripts or relying on boiler plate such as that which is provided by the Scalatra project. So I don’t really know much about building a Scala project or using the build tooling, sbt.
Today I started work on a mini-app that won’t be based on processing http requests. aka, no Scalatra. But I quickly realized I don’t know how to build such a project. So let’s figure it out.
The goal: build an sbt project that can compile code into a jar, which can then be run in a Docker container.
I’ve gained much Scala knowledge from Alvin Alexander and I turned again to him here. I based this post on two of his, but with some special modifications for a different version of scala along with my own end goal of running in docker:
- How to create an SBT project directory structure
- How to compile, run, and package a Scala project with SBT
First, create and cd
to a new directory and lay out the project structure:
Then create the sbt build definition file:
Inside build.sbt
:
Now we need to create our app entrypoint. Since we are in the land of the jvm, this means we need a class with a main()
method. Here’s a good intro to the main() method
inside Main.scala
That’s really it. Now we can run the program:
sbt also makes it easy to create a jar for distribution and deployment. We can then run the resulting jar using the scala compiler:
Sweet. Now let’s Dockerize it to complete the starter pack.
inside Dockerfile
let’s copy over our jar and provide the run command:
what the….
What, wtf is that? I thought we added our main method to the class?
We did…but the problem is we did not set an explicit main class in our build definition. While the scala compiler can detect how to start the app, the java runtime is unable to.
No problem. There’s an sbt plugin we can use to specify our main class: sbt assembly
update build.sbt
to the following:
side note: the :=
operator in a sbt build file is apparently to type the value as a string
Now we are really ready to roll.
Now we just need to update our Dockerfile with the new assembly jar:
Success! I’m looking forward to using this in a upcoming side project.
Grab the repo here: https://github.com/lombardo-chcg/sbt-project-starter