Learn Scala 3 Fast: Github Examples

Note 3: Something You’ll See in the Github Examples

As I created the Github repository of examples, I realized that there’s one thing I need to mention here in the book, and it goes as follows.

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

val a = {
    println("Hello")
    42
}

When you do this, the value of the last expression inside the code block is what’s assigned to the variable a. So in this example the println statement executes, and then the last expression inside the block is the integer value 42. If you copy and paste that code into the REPL, you’ll see that a has the type Int and the value 42:

scala> val a = {
     |     println("Hello")
     |     42
     | }
     | 
Hello
val a: Int = 42

You can use this technique anywhere you want to in your Scala code, and if there’s a second book in this series I’ll explain it more there.

This “block of code” technique is used all the time in Scala, so I’m glad that the issue I ran into forced me to mention it here.

The scope of variables inside a block

But for the purposes of this book’s examples, I use this technique for another reason: Any variables that are declared inside a block can only be seen within that block.

In the book’s Github repository I use curly braces any time I use the same variable name more than once in a file. For example, if I use the variable name smallInts in the filter lesson, like this:

val smallInts = ints.filter(_ < 3)
println(smallInts)

and then use that name again in the same file, I can enclose one or both instances in the Github examples inside curly braces:

// 1st example
{
val smallInts = ints.filter(_ < 3)
println(smallInts)
}

// 2nd example
{
val smallInts = ints.filter(i => i < 3)
println(smallInts)
}

This technique lets me use the same variable names in the examples that I use in the book’s lessons, and I hope this helps you follow the examples more easily.

I don’t use this second technique to control scope in my normal Scala code, but when I started creating the Github repository I thought this was the best way to keep the same variable names there that I use in the book.

If this doesn’t make sense yet — fear not! — I believe it will make sense after you see the lessons on variable names, and then the lessons about the filter method.