Skip to Content
Course content

179: Scala Scripting with Scala-CLI

Click on the "Edit" button in the top corner of the screen to edit your slide content.

By now, you're probably used to the ritual of creating a full sbt project: the build.sbt, the nested folder structure, and the long wait for the first compile. It's great for enterprise apps, but it's a nightmare when you just want to write a 50-line script to automate a task or poke at an API. That's where Scala-CLI comes in. It treats Scala more like Python or Ruby, letting you run a single file while still keeping the power of the JVM.

Ditching the sbt overhead

I've got a recurring need to check the star count of a few GitHub repositories to track some libraries I'm eyeing. Instead of a full project, I'm just going to create a file called stars.scala. One of the best things about Scala-CLI is that we can skip the object Main extends App boilerplate and just write code at the top level.

// stars.scala
val repo = "typelevel/cats-effect"
println(s"Fetching stars for $repo...")
// I'll add the actual HTTP logic in a second

To run this, I just hit scala-cli run stars.scala in my terminal. It's nearly instantaneous because there's no heavy project initialization happening behind the scenes.

Adding libraries without a build file

Now, I need to actually hit the GitHub API. I don't want to write raw Java HttpURLConnection code—that's a miserable experience. I'll use sttp for the request and upickle for the JSON parsing. Normally, this would mean editing a build.sbt file. With Scala-CLI, I use "using" directives right at the top of the file.

//> using dep "com.softwaremill.sttp.client3::core"
//> using dep "com.lihaoyi::upickle::scala_2.13"

import sttp.client3._
import upickle.default._

val repo = "typelevel/cats-effect"
val backend = HttpClientSyncBackend()
val response = basicRequest
  .get(s"https://api.github.com/repos/$repo")
  .header("User-Agent", "Scala-CLI-Script")
  .send(backend)

println(response.body)

The //> using dep lines are the magic here. Scala-CLI reads these comments, fetches the dependencies from Maven Central, and handles the classpath for you automatically.

Oops, I missed a dependency

I wanted to parse the JSON to get just the stargazers_count field, so I tried to define a case class and use read`json`. I wrote the code, hit run, and immediately got a ClassNotFoundException. I realized I had added the core upickle dependency, but I forgot that for certain Scala versions or specific JSON features, I might need the companion library or a specific Scala version suffix.

Actually, looking closer, I had a typo in my dependency string—I used a colon where there should have been a double-colon for the Scala version mapping. It's a small mistake, but it's a classic "scripting" moment where you're moving faster than you're thinking. I fixed it to "com.lihaoyi::upickle::scala_2.13", and suddenly everything clicked into place.

Polishing the tool

To make this actually useful, I don't want to hardcode the repo name. I'll use args, which Scala-CLI provides as a built-in array of strings containing the command-line arguments.

//> using dep "com.softwaremill.sttp.client3::core"
//> using dep "com.lihaoyi::upickle::scala_2.13"

import sttp.client3._
import upickle.default._

if (args.isEmpty) {
  println("Please provide a repo name (e.g., 'owner/repo')")
  System.exit(1)
}

val repo = args(0)
val backend = HttpClientSyncBackend()
val response = basicRequest
  .get(s"https://api.github.com/repos/$repo")
  .header("User-Agent", "Scala-CLI-Script")
  .send(backend)

response.body match {
  case Some(body) => 
    val json = ujson.read(body)
    val stars = json("stargazers_count").num
    println(s"The repo $repo has $stars stars!")
  case None => 
    println("Failed to fetch data.")
}

Now I can run scala-cli run stars.scala "scala/scala3" and get an immediate answer. If I want to distribute this to a teammate, I don't have to give them a whole git repo; I just send them this one file. They run it with Scala-CLI, and the dependencies are resolved automatically based on those //> using directives.




📋 Practical Task

Build a Currency Conversion Script

Your task is to create a Scala-CLI script named convert.scala that fetches the current exchange rate between two currencies and converts a given amount.

  • Use the free https://open.er-api.com/v6/latest/USD API (or a similar public currency API) to get current rates.
  • Use //> using dep to include sttp for the HTTP request and upickle for JSON parsing.
  • The script should accept three command-line arguments: amount, fromCurrency, and toCurrency (e.g., scala-cli run convert.scala 100 USD EUR).
  • The script should output the converted amount formatted to two decimal places.
  • Ensure you handle the case where the user provides an incorrect number of arguments by printing a helpful usage message.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.