Kotlin Conditional Statements: The Decision Makers of Your Code! 🧠🚦
Imagine you're playing a video game 🎮, and you need to decide:
- If your health is low, drink a potion.
- If an enemy attacks, defend or fight.
- If you find treasure, collect it!
Just like in games, your Kotlin programs also need to make decisions based on conditions. This is where conditional statements (if-else
and when
) come in! 🚀
In this blog, we’ll dive deep into Kotlin’s conditional statements, their types, features, and examples, and how they make your code smarter! 🏆
1️⃣ What Are Conditional Statements? 🤔
A conditional statement helps your code make decisions based on conditions.
💡 Think of it like this:
- "If it's raining, take an umbrella." ☔
- "If it's sunny, wear sunglasses." 🕶️
In Kotlin, we use:
✅ if-else
→ When we have two or more possible conditions.
✅ when
→ When we have multiple options (like a switch case).
Let’s explore both in detail! 🧐
2️⃣ if-else
: The Basic Decision Maker 🏗️
🔹 Syntax of if-else
if (condition) {
// Code runs if condition is true
} else {
// Code runs if condition is false
}
🔹 Example: Checking Age for Voting 🗳️
val age = 18
if (age >= 18) {
println("You can vote! ✅")
} else {
println("Sorry, you are too young to vote. ❌")
}
🔹 If age
is 18 or more, it prints ✅.
🔹 Otherwise, it prints ❌.
3️⃣ if-else if-else
: Multiple Conditions 🔄
What if there are more than two possibilities? Use else if
!
🔹 Example: Grading System 🎓
val marks = 85
if (marks >= 90) {
println("Grade: A 🎯")
} else if (marks >= 75) {
println("Grade: B ✅")
} else if (marks >= 50) {
println("Grade: C ⚠️")
} else {
println("Grade: F ❌")
}
📌 How It Works?
- If
marks
≥ 90, print "Grade A". - Else if
marks
≥ 75, print "Grade B". - Else if
marks
≥ 50, print "Grade C". - Else, print "Grade F".
4️⃣ if
as an Expression (Returning Values) 🎯
Kotlin allows if
as an expression, meaning it can return a value! 🚀
🔹 Example: Finding the Maximum of Two Numbers 🏆
val a = 10
val b = 20
val max = if (a > b) a else b
println("The maximum value is $max") // Output: The maximum value is 20
💡 No need for {}
if it’s a single expression!
- If
a > b
,max = a
- Otherwise,
max = b
5️⃣ when
: The Smarter Switch Case! 🚦
Instead of writing multiple if-else if
, Kotlin provides when
, which is more readable and powerful!
🔹 Syntax of when
when (value) {
case1 -> // Code
case2 -> // Code
else -> // Default case
}
6️⃣ when
with Constants 📌
🔹 Example: Checking the Day of the Week 📅
val day = 3
when (day) {
1 -> println("Monday")
2 -> println("Tuesday")
3 -> println("Wednesday") // ✅ Matches this case
4 -> println("Thursday")
else -> println("Invalid day")
}
Output: Wednesday
✅
7️⃣ when
with Ranges & Multiple Values 🎯
🔹 Example: Categorizing Age Groups 👶🧑👴
val age = 25
when (age) {
in 0..12 -> println("Child 👶")
in 13..19 -> println("Teenager 🧑")
in 20..59 -> println("Adult 💼")
else -> println("Senior Citizen 👴")
}
💡 How It Works?
in 0..12
→ If age is between 0-12, print "Child".in 13..19
→ If age is between 13-19, print "Teenager".in 20..59
→ If age is between 20-59, print "Adult".else
→ Anything outside these ranges prints "Senior Citizen".
8️⃣ when
as an Expression (Returning Values) 🔥
Just like if
, when
can return a value!
🔹 Example: Finding the Type of an Object 🧐
fun checkType(obj: Any): String {
return when (obj) {
is String -> "It's a String 📜"
is Int -> "It's an Integer 🔢"
is Boolean -> "It's a Boolean ⚡"
else -> "Unknown type 🤷"
}
}
println(checkType(42)) // Output: It's an Integer 🔢
🔹 Using is
to check types is a powerful Kotlin feature! 🚀
9️⃣ when
with Functions and Enum Classes 🎨
🔹 Example: Using when
with Enums
enum class TrafficLight { RED, YELLOW, GREEN }
fun action(light: TrafficLight) {
when (light) {
TrafficLight.RED -> println("Stop 🚦")
TrafficLight.YELLOW -> println("Get Ready ⏳")
TrafficLight.GREEN -> println("Go! 🏁")
}
}
action(TrafficLight.GREEN) // Output: Go! 🏁
✅ Perfect for handling multiple fixed values!
🔟 if
vs when
: When to Use What? 🤔
Feature | if-else | when |
---|---|---|
Best for | Simple conditions | Multiple conditions |
Readability | Less readable for many cases | More readable |
Expression? | Yes | Yes |
Handles ranges? | Yes | Yes (better) |
Works with Enums & Types? | No | Yes ✅ |
🔟 Conclusion: Kotlin Makes Decisions Smartly! 🚀
🔹 Use if-else
when handling simple conditions.
🔹 Use when
when checking multiple values (it’s more readable).
🔹 Use expressions (if
and when
) to return values.
🔹 Leverage when
with ranges, types, and enums for cleaner code.
Now that you know how Kotlin makes decisions, go ahead and try some conditional magic in your code! 🪄✨
💬 Which one do you prefer: if-else
or when
? Let me know in the comments! ⬇️😊