KOTLIN Tutorial



IF ELSE IN KOTLIN


πŸ”€ if-else in Kotlin

The if statement allows conditional execution of code. Kotlin supports traditional if-else blocks, as well as if as an expression. Let’s explore both.


1️⃣ Basic if Statement

Let’s start with a simple example:

fun main() {
    val age = 20

    if (age >= 18) {
        println("You're eligible to vote πŸ—³οΈ")
    }
}
  
βœ… Try this: Change age to 17. What will happen?

2️⃣ if-else Statement

Now let’s add a fallback when the condition isn’t true:

fun main() {
    val temp = 35

    if (temp > 30) {
        println("It's hot outside! β˜€οΈ")
    } else {
        println("It's comfortable 😊")
    }
}
  
πŸ” Think: What if temp = 30? Will it print hot or comfortable?

3️⃣ if-else if Ladder

Use this when you have more than two conditions to check:

fun main() {
    val score = 82

    if (score >= 90) {
        println("Grade: A πŸ†")
    } else if (score >= 75) {
        println("Grade: B πŸ‘")
    } else if (score >= 60) {
        println("Grade: C 😊")
    } else {
        println("Grade: D 😬")
    }
}
  
🎯 Challenge: Modify the score to test different grades!

4️⃣ if as an Expression 🧠

Kotlin lets you return values directly from if. No need for ternary operator!

fun main() {
    val time = 22
    val greeting = if (time < 18) "Good Day" else "Good Evening"

    println(greeting)
}
  
πŸ§ͺ Explore: Can you write an if-expression that picks between two emojis based on mood?

5️⃣ Real World Mini Test 🧩

What does this code print?

fun main() {
    val isRaining = false
    val isCloudy = true

    if (isRaining) {
        println("Take an umbrella β˜”")
    } else if (isCloudy) {
        println("Might rain later, stay alert πŸŒ₯️")
    } else {
        println("Enjoy the sunshine! 🌞")
    }
}
  
❓ Guess the Output: Think before running! What gets printed?

6️⃣ Quick Summary

  • βœ”οΈ Use if to run code conditionally.
  • βœ”οΈ Add else for fallback logic.
  • βœ”οΈ Use else if for multiple checks.
  • βœ”οΈ You can use if as an expression (returning a value).
πŸŽ‰ You're ready to build smart Kotlin programs with decisions!

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review