Scala 3 · 36 of 42

Optional braces & new control syntax

Scala 3’s most visible change: braces are optional. Indentation defines structure, the way it does in Python, except everything is still statically typed and checked by the compiler.

Alongside it came a new control syntax:

  • if cond then a else b: no parentheses around the condition
  • while cond do body
  • for x <- xs do body (and for x <- xs yield expr for comprehensions)

Both changes are optional. Braces and the old parenthesized style still compile, and you’ll see plenty of both in the wild. Pick a style per codebase and stay consistent.

For long indented blocks, an optional end marker (end classify, end if, end while) documents where a block finishes.

Tip: try removing an indentation level in the editor and running: the compiler will tell you exactly what it expected.
//new control syntax: no parentheses, `then` and `do` keywords
val x = 7

if x % 2 == 0 then
  println("even")
else
  println("odd")

var i = 0
while i < 3 do
  println(s"i = $i")
  i += 1

for fruit <- List("apple", "banana", "cherry") do
  println(fruit)

//indentation instead of braces: like Python, but typed
def greet(name: String): String =
  val upper = name.capitalize
  s"Hello, $upper!"

println(greet("world"))

//`end` markers (optional) help readability in long blocks
def classify(n: Int): String =
  if n < 0 then "negative"
  else if n == 0 then "zero"
  else "positive"
end classify

println(classify(-5))

//the old style still compiles; both are valid Scala 3
def greetOldStyle(name: String): String = {
  val upper = name.capitalize
  s"Hello, $upper!"
}
println(greetOldStyle("braces"))

Contents

Scala basics

  1. Overview
  2. Scalculator
  3. Operators are methods
  4. Variables
  5. Final variables
  6. Printing values
  7. String interpolation
  8. String formatting
  9. Useful operations
  10. Method definition
  11. Method definition 2
  12. Method definition 3
  13. Anonymous functions
  14. Anonymous functions 2
  15. Return multiple values
  16. Declare multiple variables
  17. Assign multiple variables
  18. Loops using while
  19. Loops using for
  20. Loops without loops
  21. If
  22. Match as a switch
  23. Arrays
  24. Lists
  25. Sets
  26. Maps
  27. Mutable collections
  28. Collections: accessing elements
  29. Collections: concatenation
  30. Mutable collection operations
  31. Immutable collections with var
  32. Collections: useful methods
  33. Classes
  34. Classes, continued

What's new in Scala 3

  1. Scala 3: what changed
  2. Optional braces & new control syntax
  3. Top-level definitions & @main
  4. Enums & ADTs
  5. Extension methods
  6. given & using
  7. Union & intersection types
  8. Smaller niceties