Control Structures
In Scala, almost everything is an expression that returns a value — including if and match.
On this page · 5 min · Beginner
On this page
- In simple words
- Learning objectives
- Explanation
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Beginner
- Updated
- Oct 30, 2026
Related tutorials
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#
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)
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#
- if returns the delivery charge directly.
- for with a range loops three times.
- A guard and yield build a filtered collection.
- match with guards picks a grade.
Real-world use case#
Pricing rules become single expressions assigned to vals, avoiding mutable variables.
Common mistakes#
It returns Unit when false. Always include else when assigning.
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
val evens = for n <- 1 to 10 if n % 2 == 0 yield n
Mini quiz#
What does 1 until 5 contain?
Want more? Practise all Scala MCQs · Scala interview questions
My notes#
Saved in this browser.