Chapter 6: Control Flow: Conditions
Control Flow – Conditions — this is the chapter where Kotlin really starts to feel like magic compared to Java!
Kotlin’s control flow is cleaner, more expressive, and much more powerful — especially the when expression (which is like a super-charged switch on steroids) and if as an expression.
We’re going to go super slowly, like we’re sitting together in a quiet Bandra café with cutting chai ☕ — I’ll explain every concept with real-life analogies, lots of copy-paste examples, step-by-step breakdowns, tables, common mistakes, and fun facts so everything sticks perfectly.
Let’s dive in!
1. if as Expression – Kotlin’s First Big Win
In Java → if is just a statement (does something, no return value). In Kotlin → if is an expression → it returns a value!
Real-life analogy: In Java → “If it’s raining, take umbrella” → just an instruction. In Kotlin → “If it’s raining, take umbrella, otherwise take sunglasses” → you get something back (umbrella or sunglasses).
Basic if statement (same as Java)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
fun main() { val temperature = 28 if (temperature > 30) { println("It's very hot!") } else if (temperature > 20) { println("Nice weather") } else { println("Cold day") } } |
if as expression → returns the last expression of the block
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
fun main() { val temperature = 25 val advice = if (temperature > 30) { "Very hot! Stay indoors" } else if (temperature > 20) { "Perfect Mumbai weather!" } else { "Take a jacket" } println("Advice: $advice") // Perfect Mumbai weather! } |
Even shorter (single-line branches)
|
0 1 2 3 4 5 6 7 |
val advice = if (temperature > 30) "Very hot!" else "Nice weather" println(advice) |
Very common pattern: assign result directly
|
0 1 2 3 4 5 6 |
val max = if (a > b) a else b // Like ternary operator, but better! |
2. when – Super-Powered Switch (Kotlin’s Star Feature)
when is much more powerful than Java’s switch. It’s an expression (returns value), supports types, ranges, collections, etc.
Basic when as statement
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
fun main() { val day = 3 when (day) { 1 -> println("Monday – Start the week!") 2 -> println("Tuesday") 3 -> println("Wednesday – Halfway!") 4 -> println("Thursday") 5 -> println("Friday – Party time!") 6, 7 -> println("Weekend – Relax! 🎉") // Multiple values else -> println("Invalid day") } } |
when as expression (returns value – most common!)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
fun getDayType(day: Int): String { return when (day) { 1, 2, 3, 4, 5 -> "Weekday" 6, 7 -> "Weekend" else -> "Invalid day" } } fun main() { println(getDayType(3)) // Weekday println(getDayType(6)) // Weekend } |
Powerful features of when
- Type checking (smart cast!)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun describe(obj: Any) { when (obj) { is String -> println("String of length ${obj.length}") is Int -> println("Number: $obj") is List<*> -> println("List with ${obj.size} items") else -> println("Unknown type") } } |
- Ranges (super useful!)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
val score = 85 when (score) { in 90..100 -> println("A+ – Outstanding!") in 80..89 -> println("A – Excellent") in 70..79 -> println("B – Good") in 60..69 -> println("C – Average") else -> println("Needs improvement") } |
- Collection check with in
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
val allowedCities = listOf("Mumbai", "Pune", "Delhi") val city = "Mumbai" when { city in allowedCities -> println("$city is allowed!") else -> println("$city not allowed") } |
- Without argument (like if-else chain)
|
0 1 2 3 4 5 6 7 8 9 10 |
when { temperature > 30 -> println("Very hot!") temperature > 20 -> println("Nice") else -> println("Cold") } |
3. Ranges in Kotlin – Very Powerful
Kotlin has beautiful range syntax — used everywhere (in when, for, if, etc.)
| Syntax | Meaning | Includes end? | Example |
|---|---|---|---|
| .. | Closed range (includes both ends) | Yes | 1..5 → 1,2,3,4,5 |
| until | Open range (excludes end) | No | 1 until 5 → 1,2,3,4 |
| downTo | Decreasing range | Yes | 5 downTo 1 → 5,4,3,2,1 |
| step | Jump by step | — | (1..10).step(2) → 1,3,5,7,9 |
Examples
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Check if number is in range val marks = 85 if (marks in 80..100) println("A grade!") // Loop with range for (i in 1..5) print("$i ") // 1 2 3 4 5 for (i in 5 downTo 1) print("$i ") // 5 4 3 2 1 for (i in 1..10 step 2) print("$i ") // 1 3 5 7 9 for (i in 10 until 15) print("$i ") // 10 11 12 13 14 |
4. in Operator with Collections
in works beautifully with lists, sets, maps, strings, ranges…
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
val fruits = listOf("Apple", "Banana", "Cherry") println("Apple" in fruits) // true println("Mango" !in fruits) // true (not in) val allowed = setOf("Mumbai", "Pune") val userCity = "Mumbai" println(userCity in allowed) // true val password = "Kotlin123" println("Kotlin" in password) // true |
5. Quick Recap Table (Your Cheat Sheet)
| Feature | Kotlin Way (Best Practice) | Java Equivalent (for comparison) |
|---|---|---|
| if as expression | val max = if (a > b) a else b | int max = (a > b) ? a : b; |
| when as statement | when (day) { 1 -> … } | switch (day) { case 1: … } |
| when as expression | val type = when (day) { … } | No direct equivalent |
| Range (inclusive) | 1..10 | No direct equivalent |
| Range (exclusive) | 1 until 10 | No direct equivalent |
| in operator | x in list, x in 1..10 | list.contains(x) |
6. Common Newbie Mistakes & Fixes
| Mistake | Problem | Fix |
|---|---|---|
| Using == instead of in for ranges | if (marks == 80..100) → wrong! | Use marks in 80..100 |
| Forgetting else in when expression | Compile error (when must be exhaustive) | Add else -> … |
| Using switch keyword | Doesn’t exist in Kotlin | Use when instead |
| Writing if without else in expression | Compile error (must return value) | Always provide else branch |
| Confusing .. and until | Off-by-one errors | Remember: .. includes end, until excludes |
7. Homework for You (Let’s Make It Fun!)
- Basic Ask user for a number (using readln()) → use when to print if it’s positive, negative, or zero.
- Medium Ask user for marks (0–100) → use when with ranges to print grade (A+, A, B, C, Fail).
- Advanced Write a function fun getDayMessage(day: Int) that returns message using when (Monday → “Start week!”, Weekend → “Relax!”).
- Fun Use in to check if a character is vowel → ask user for a letter → print “Vowel” or “Consonant”.
- Challenge Fix this buggy code:
Kotlin012345678val score = 85val grade = if (score > 90) "A" // Missing else!println(grade)
You’ve just unlocked Kotlin’s most loved control flow — when and expression-style if!
