0
0
KotlinHow-ToBeginner · 3 min read

How to Use If Else in Kotlin: Simple Guide with Examples

In Kotlin, use if to run code when a condition is true, and else to run code when it is false. The syntax is if (condition) { ... } else { ... }. You can also chain multiple conditions using else if.
📐

Syntax

The if statement checks a condition inside parentheses. If the condition is true, the code inside the following block runs. The else block runs if the condition is false. You can add else if to check more conditions.

  • if (condition): checks if condition is true
  • { ... }: code block to run if true
  • else if (condition): checks another condition if previous was false
  • else: runs if all previous conditions are false
kotlin
if (condition) {
    // code if condition is true
} else if (anotherCondition) {
    // code if anotherCondition is true
} else {
    // code if all conditions are false
}
💻

Example

This example shows how to use if else to check a number and print if it is positive, negative, or zero.

kotlin
fun main() {
    val number = 5
    if (number > 0) {
        println("Number is positive")
    } else if (number < 0) {
        println("Number is negative")
    } else {
        println("Number is zero")
    }
}
Output
Number is positive
⚠️

Common Pitfalls

One common mistake is forgetting the curly braces { } for the code blocks, which can cause only the next line to be part of the if or else. Another is mixing up the conditions or missing the else block when needed.

Also, remember that if in Kotlin can be used as an expression to return a value, which is different from some other languages.

kotlin
fun main() {
    val x = 10
    // Wrong: missing braces, only next line is conditional
    if (x > 0)
        println("Positive")
    println("This always prints")

    // Right: braces include both lines
    if (x > 0) {
        println("Positive")
        println("This prints only if x > 0")
    }
}
Output
Positive This always prints Positive This prints only if x > 0
📊

Quick Reference

KeywordPurposeExample
ifChecks a conditionif (x > 0) { ... }
else ifChecks another condition if previous is falseelse if (x == 0) { ... }
elseRuns if all previous conditions are falseelse { ... }

Key Takeaways

Use if to run code when a condition is true and else for the false case.
Always use curly braces { } to group multiple statements inside if or else blocks.
else if lets you check multiple conditions in order.
In Kotlin, if can also return a value, making it an expression.
Be careful with indentation and braces to avoid unexpected behavior.