Kotlin Conditions


Kotlin Conditions – Controlling the Flow

In real life, you make choices all the time:

  • If it's raining → Take an umbrella.
  • If you're hungry → Grab a snack.

Similarly, in Kotlin, conditions help your code make decisions and act accordingly.


The Classic if Statement

Use if to perform something only when a rule is true:

val age = 18  

if (age >= 18) {     
   println("You're allowed to vote!")
 } 

If the age is 18 or more, the message appears. Otherwise — silence.


else – The “Otherwise” Option

Want a backup plan if the condition fails? Add else:

val score = 45  

if (score >= 50) {    
    println("Passed") 
} else {     
    println("Try again")
 } 

This gives two paths: one if it's true, one if not.


else if – Multiple Paths

What if there are several outcomes?

val marks = 85  

if (marks >= 90) {     
    println("Grade: A+") 
} else if (marks >= 80) {     
    println("Grade: A") 
} else if (marks >= 70) {     
    println("Grade: B") 
} else {    
   println("Keep improving")
} 

Checks happen top-down — first match wins.


Short if – Inline Style

Use a one-liner for simple choices:

val isLoggedIn = true  

If (isLoggedIn) println("Welcome back!") 

Compact and clean.


if as an Expression – Return a Value

You can assign the result of an if block directly into a variable:

val temperature = 25 
val weather = if (temperature > 30) "Hot" else "Pleasant" 

Println(weather)  // Outputs: Pleasant 

Neat trick for shorter, readable code.


Nested if – Inside Layers

Conditions inside conditions?

val user = "admin" 
val password = "1234"  

if (user == "admin") {     
     if (password == "1234") {         
             println("Access granted")    
      } else {         
            println("Wrong password")     
      } 
} else {     
       println("Unknown user") 
} 

Only moves deeper if outer check passes.


Recap Table

Type Syntax Example Use Case
Basic if if (x > 5) Single condition
else else { ... } Alternative path
else if else if (x == 3) Chain of decisions
Inline if if (isTrue) println("Yes") Short checks
Expression val msg = if (ok) "Yes" else "No" Store outcomes in variable
Nested if (a) { if (b) { ... } } Step-by-step validation

Prefer Learning by Watching?

Watch these YouTube tutorials to understand KOTLIN Tutorial visually:

What You'll Learn:
  • 📌 Kotlin If Else Statement Explained | Basics Of Kotlin For Beginners | Kotlin Tutorial | Simplilearn
  • 📌 #11 Kotlin Tutorial | If Else Expression
Previous Next