Scala If Else

The if expression lets your program make decisions. Based on a condition, it runs one block of code or another. In Scala, if is an expression — it produces a value — which makes it more powerful than the if statement found in many other languages.

Basic if

val temperature = 38

if temperature > 35 then
  println("It's very hot today")

If the condition temperature > 35 is true, the code inside runs. If false, nothing happens and execution continues below.

if-else

val marks = 72

if marks >= 50 then
  println("Pass")
else
  println("Fail")
// Pass

if as an Expression

Unlike Java, Scala's if returns a value. You can assign the result directly to a variable:

val score = 85
val grade = if score >= 90 then "A" else if score >= 75 then "B" else "C"
println(grade)   // B

score = 85
   │
   ├── 85 >= 90? No
   ├── 85 >= 75? Yes → "B"
   └── result: "B" stored in grade

if-else if-else Chain

val bmi = 22.5

val category =
  if bmi < 18.5 then "Underweight"
  else if bmi < 25.0 then "Normal"
  else if bmi < 30.0 then "Overweight"
  else "Obese"

println(s"BMI category: $category")   // BMI category: Normal

Multi-line if Blocks

val balance = 5000
val withdrawal = 3000

if withdrawal <= balance then
  val newBalance = balance - withdrawal
  println(s"Withdrawal successful")
  println(s"New balance: ₹$newBalance")
else
  println("Insufficient funds")
  println(s"Available: ₹$balance")

Nested if

val age = 20
val hasId = true

if age >= 18 then
  if hasId then
    println("Entry allowed")
  else
    println("Please show ID")
else
  println("Entry not allowed (underage)")

         age >= 18?
        /          \
      Yes           No
       │             └── "Entry not allowed"
    hasId?
    /    \
  Yes     No
   │       └── "Please show ID"
"Entry allowed"

if with Boolean Operators

val username = "admin"
val password = "secret123"

if username == "admin" && password.length >= 8 then
  println("Login successful")
else
  println("Login failed")

// Multiple conditions
val x = 15
if x > 10 && x < 20 then
  println(s"$x is between 10 and 20")

if Inside println

val n = 7
println(if n % 2 == 0 then "even" else "odd")   // odd

Unit Result from if Without else

When an if has no else branch, the result type is Unit. This is fine for side effects like printing, but do not assign it to a value:

val flag = true

// Fine — side effect only, no value needed
if flag then println("Flag is set")

// Avoid this pattern — result is Unit, not useful
val result = if flag then "yes"   // result type: Any (bad)

Always pair if with else when you want to produce a value.

Inline if in String Interpolation

val count = 5
val itemWord = if count == 1 then "item" else "items"
println(s"You have $count $itemWord in your cart")
// You have 5 items in your cart

// Or inline:
println(s"You have $count ${if count == 1 then "item" else "items"} in your cart")

Replacing if-else with match

When you have many conditions, match is often cleaner than a chain of else if:

// if-else chain (gets unwieldy)
val day = 3
val name1 =
  if day == 1 then "Monday"
  else if day == 2 then "Tuesday"
  else if day == 3 then "Wednesday"
  else "Other"

// match (cleaner)
val name2 = day match
  case 1 => "Monday"
  case 2 => "Tuesday"
  case 3 => "Wednesday"
  case _ => "Other"

println(name2)   // Wednesday

Practical Examples

Age Verification

def checkAge(age: Int): String =
  if age < 0 then "Invalid age"
  else if age < 13 then "Child"
  else if age < 18 then "Teenager"
  else if age < 60 then "Adult"
  else "Senior"

println(checkAge(8))    // Child
println(checkAge(15))   // Teenager
println(checkAge(35))   // Adult
println(checkAge(72))   // Senior

Discount Calculator

def applyDiscount(price: Double, memberYears: Int): Double =
  val discountRate =
    if memberYears >= 5 then 0.20
    else if memberYears >= 2 then 0.10
    else 0.05
  price * (1 - discountRate)

println(f"${applyDiscount(1000, 6)}%.2f")   // 800.00
println(f"${applyDiscount(1000, 3)}%.2f")   // 900.00
println(f"${applyDiscount(1000, 1)}%.2f")   // 950.00

Scala 2 Style (Curly Braces)

Scala 3 introduced the then keyword. In Scala 2 (and still valid in Scala 3), you use parentheses for the condition and braces for the body:

// Scala 2 style (works in Scala 3 too)
if (temperature > 35) {
  println("Hot")
} else {
  println("Cool")
}

// Scala 3 style (cleaner)
if temperature > 35 then
  println("Hot")
else
  println("Cool")

Both styles produce identical behavior. New Scala 3 code generally uses the indentation-based style.

Leave a Comment

Your email address will not be published. Required fields are marked *