Skip to content

Scala code blocks

Supersimple's Scala blocks let you run Scala 3 code on the JVM, including accessing data from other blocks in the same exploration.

TIP

Code blocks are a convenient way for engineers to share the results of more advanced work with the rest of their teams, without needing others to set up full coding environments.

Usage

Create a new Scala block via the "New block" button, and choose Scala from the Code dropdown.

Blocks run on Scala 3.3 and Java 21. Your code is compiled on every run, so expect a few seconds before the result appears, more on the first run after a while.

Using data from other blocks

You can access data from other blocks in your exploration with getBlock, which is available without an import:

scala
val block = getBlock("User") // data model name or block title

block.rows.size

getBlock returns a Block(fields, rows). rows is a Seq[Map[String, Any]] keyed by field key, with values as Long, Double, String, Boolean or null, and fields is a Seq[Field] describing each column with its key, name and Supersimple type:

scala
case class Signup(user: String, at: String)

getBlock("Event").rows
  .filter(row => row("type") == "signup")
  .map(row => Signup(row("user_id").toString, row("created_at").toString))

Libraries

Libraries from Maven Central are declared with //> using dep directives, the same way as in Scala CLI, and imported as usual:

scala
//> using dep org.typelevel::cats-core:2.13.0
import cats.syntax.all.*

val totals = getBlock("Order").rows.map(row => row("total").asInstanceOf[Double])

totals.combineAll

Directives can appear anywhere in the block. Libraries are downloaded the first time a block uses them and reused by later runs.

Outputting data

Similarly to Jupyter notebooks, the last expression in a block is automatically outputted as the block's result.

  • A Seq of Maps or of case class instances becomes a Supersimple table, with column types inferred from the values.
  • Strings, numbers and booleans are shown as text.
  • Other collections and case classes are shown as formatted JSON.

Anything written with println appears in the block's log rather than in the output.

To render custom output, return a Map with an explicit type:

scala
Map("type" -> "html", "htmlString" -> "<h1>Hello</h1>")
scala
Map("type" -> "image", "base64ImageString" -> "data:image/png;base64,...")