Learn Scala 3 Fast: Significant Indentation Syntax

Note 1: Significant Indentation Syntax

A BIG change from Scala 2 to Scala 3 is the introduction of something known as significant indentation syntax. This means that instead of writing code like this in Scala 2:

for (i <- 1 to 10) {
    println(i)
}

we now write that code without the curly braces, like this:

for i <- 1 to 10 do
    println

In short, Scala 3 gets rid of most curly braces and indentation is now important and significant. This new approach is consistent with languages like Python and Haskell, and more importantly, it’s cleaner and easier to read. And because programmers spend about 10 times as much time reading code as we do writing code, readability is huge. (I won’t be surprised if all major programming languages adopt this new style in the next 10 years.)

Indenting with four spaces

With this new indentation style I prefer to indent my code with four spaces, and that’s what this book uses. Many Scala programmers use two spaces, but I think four spaces makes the code easier to read, so that’s why I use it.

I also find that using four spaces makes it more obvious when your functions are getting too long. When you’re indenting your code so much that it starts going off the right side of the screen, that’s a great hint that you should probably break your functions down into smaller functions.

About those curly braces

I need to mention that technically you can still use curly braces if you want, but pretty much every book and learning resource for Scala 3 — including those created by the Scala Center and the creator of Scala, Martin Odersky — uses the significant indentation syntax. So you can still use curly braces, but it’s not the recommended approach.

books by alvin