home search about rss feed twitter ko-fi

JIT: Code Blocks (Closures) (Scala 3 Video)

Before we get into the next TDL lesson, I need to cover a Scala language feature I refer to as code blocks, or blocks of code. I’ve seen in other languages that this feature can be called a closure (but I think there are multiple definitions of that term).

In short, you create a block of code in Scala using curly braces, like this:

val a = {
    // a block of code
    println("hi mom")
    42
}

The result of a code block is its final value. In this example that value is the integer 42, so if you want to explicitly declare a’s type, it’s an Int:

val a: Int = {        // <== explicitly set the Int type
    // a block of code
    println("hi mom")
    42
}

Notice that any legal Scala code can be inside that code block, such as the side effect of printing to STDOUT. But from Scala’s perspective, its return type is Int.

You can demonstrate this for yourself in the Scala REPL by passing a code block to its :type command:

scala> :type { println("hi"); 42 }
Int
                                                                                                                     
scala> :type { println("hi"); "dude" }
String

Again, notice that the type of the code block is that last value returned by it. And if that last value is something that yields Unit, that’s the block’s type:

scala> :type { val a = 73; println("hi") }
Unit

As we get ready for the next lesson, being aware of code blocks in Scala is one thing you’ll need to know.

Update: All of my new videos are now on
LearnScala.dev