Scala · Basics

Control Structures

In Scala, almost everything is an expression that returns a value — including if and match.

Beginner 5 min Lesson 5 of 25Examples use Scala 3 (3.3 LTS or newer) with sbt or scala-cli.
Before you start:Types and Type Inference
0/25 in Scala
On this page · 5 min · Beginner

In simple words#

In many languages if is a road sign (“go left”). In Scala it’s a vending machine: put in a condition and it hands back a value you can store.

Expression
Code that produces a value.
Guard
An if condition inside a for or case.
Range
1 to 10 or 1 until 10.

Learning objectives#

  • Use if as an expression
  • Loop with for and ranges
  • Add guards to for loops
  • Use Scala 3 syntax

Explanation#

val label = if amount > 1000 then "big" else "small" — no ternary needed.

for i <- 1 to 5 do println(i) loops; 1 until 5 excludes 5.

Guards filter: for n <- 1 to 20 if n % 3 == 0 do ….

for … yield builds a new collection. while exists but is rarely needed.

Code example: Expressions and loops#

ScalaExpressions and loops Illustrative
val amount = 1499
val delivery = if amount >= 999 then 0 else 49
println(s"Delivery: ₹$delivery")


for day <- 1 to 3 do
  println(s"Day $day")


val multiplesOf3 = for n <- 1 to 15 if n % 3 == 0 yield n
println(multiplesOf3)


val grade = amount match
  case a if a > 1000 => "Gold"
  case a if a > 500  => "Silver"
  case _             => "Bronze"
println(grade)
Expected output
Delivery: ₹0
Day 1
Day 2
Day 3
Vector(3, 6, 9, 12, 15)
Gold

This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.

Step-by-step explanation#

  1. if returns the delivery charge directly.
  2. for with a range loops three times.
  3. A guard and yield build a filtered collection.
  4. match with guards picks a grade.

Real-world use case#

Pricing rules become single expressions assigned to vals, avoiding mutable variables.

Common mistakes#

if without else used as a value

It returns Unit when false. Always include else when assigning.

Mixing braces and indentation inconsistently

Pick one style per project.

Best practices#

  • Treat if/match as expressions
  • for-yield over mutable buffers
  • Guards over nested ifs
  • Consistent indentation

Remember this#

if … then … else returns a value.

to includes, until excludes.

for … yield builds collections.

Practice exercise#

Your task: Build a list of even numbers from 1 to 10 with for-yield.

Show solution
Scala Illustrative
val evens = for n <- 1 to 10 if n % 2 == 0 yield n

Mini quiz#

Control Structures quizMultiple choice Question 1 of 1

What does 1 until 5 contain?

Score so far: 0/0

Want more? Practise all Scala MCQs · Scala interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.