In this tutorial, you shall learn how to use the Kotlin if-else statement to make decisions, evaluate multiple conditions, assign values with an if expression, and write nested if-else statements with examples.

Kotlin If-Else Statement

Kotlin If Else is a decision making statement, that can be used to execute one of the two code blocks based on the result of a condition.

In this tutorial, you can learn the syntax of if-else statement, and understand how to write if-else statements in a Kotlin program with examples.

The condition supplied to an if statement must be a Boolean expression whose result is either true or false. Kotlin does not treat numbers, strings, or other values as implicit Boolean values.

Kotlin If-Else Syntax

The syntax of if else statement in Kotlin is as shown in the following.

</>
Copy
if(condition) {
    //if-block statement(s)
} else {
    //else-block statement(s)
}
  • if, else: Kotlin keywords.
  • condition: a boolean expression or something that evaluates to a boolean value.
  • () encloses condition, and {} encloses code blocks.

If the condition evaluates to true, runtime executes corresponding if-block statement(s).

If the condition evaluates to false, runtime executes corresponding else-block statement(s).

else block is optional. So, if-else without else would become a simple if statement in Kotlin.

Kotlin If-Else Execution Flow

  1. Kotlin evaluates the condition inside the parentheses.
  2. If the condition is true, Kotlin executes the statements in the if block and skips the else block.
  3. If the condition is false, Kotlin skips the if block and executes the statements in the else block.
  4. Execution then continues with the statement following the complete if-else construct.

Exactly one of the two blocks runs in a standard if-else statement.

Kotlin If-Else Examples

1. Check if a Number Is Even or Odd using If-Else

In the following program, we check if the given number is even number or odd number using an if-else statement, and print the output.

Main.kt

</>
Copy
fun main(args: Array<String>) {
    val a = 13

    if(a%2==0) {
        print("$a is even number.")
    } else {
        print("$a is odd number.")
    }
}

Output

13 is odd number.

Since a=13 is odd, a%2==0 evaluates to false. So, the else block is executed.

2. Use If-Else without Braces for Single Statements

Braces are optional if the number of statements in the corresponding block is one.

In the following example, we have only one statement in if and else blocks. So, the braces are optional for both the if and else blocks. Hence no braces.

Though braces are optional, it is recommended to use braces to enclose if or else code blocks to enhance the readability of the program.

Main.kt

</>
Copy
fun main(args: Array<String>) {
    val a = 15

    if(a%2==0)
        print("$a is even number.")
    else
        print("$a is odd number.")
}

Output

15 is odd number.

Although this form is valid, braces make future edits safer. Adding another indented statement without braces does not automatically place that statement inside the branch.

Kotlin If as an Expression

In Kotlin, if is an expression as well as a control-flow construct. It can return a value, which means you can assign the result of an if-else expression directly to a variable.

When if is used as an expression, an else branch is generally required so that a value is available for every possible condition result.

Main.kt

</>
Copy
fun main() {
    val number = 18
    val result = if (number % 2 == 0) {
        "even"
    } else {
        "odd"
    }

    println("$number is $result.")
}

Output

18 is even.

The value of the final expression in the selected block becomes the result. Here, the strings "even" and "odd" do not require an explicit return.

Write a Single-Line Kotlin If-Else Expression

A short value-producing condition can be written on one line. Kotlin does not use the Java-style ternary operator condition ? value1 : value2; the if expression provides the same result.

</>
Copy
fun main() {
    val age = 20
    val category = if (age >= 18) "Adult" else "Minor"

    println(category)
}

Output

Adult

Kotlin Else-If Ladder for Multiple Conditions

Use an else if ladder when several mutually exclusive conditions must be checked. Kotlin evaluates the conditions from top to bottom and executes the first branch whose condition is true.

Main.kt

</>
Copy
fun main() {
    val score = 76

    val grade = if (score >= 90) {
        "A"
    } else if (score >= 75) {
        "B"
    } else if (score >= 60) {
        "C"
    } else {
        "D"
    }

    println("Grade: $grade")
}

Output

Grade: B

The order of the conditions matters. Place the most restrictive or highest threshold first. If score >= 60 appeared before score >= 75, a score of 76 would match the earlier branch and the later condition would never be evaluated.

Combine Conditions in Kotlin If-Else

Kotlin provides logical operators for combining Boolean conditions:

  • && is true when both conditions are true.
  • || is true when at least one condition is true.
  • ! reverses a Boolean value.

The && and || operators use short-circuit evaluation. Kotlin evaluates the right-hand condition only when its result is needed.

</>
Copy
fun main() {
    val age = 24
    val hasTicket = true

    if (age >= 18 && hasTicket) {
        println("Entry allowed.")
    } else {
        println("Entry not allowed.")
    }
}

Output

Entry allowed.

Safely Check Nullable Values with Kotlin If-Else

An if condition is commonly used to check whether a nullable value is not null. After a suitable null check, Kotlin can smart-cast a stable value to its non-null type inside the branch.

</>
Copy
fun main() {
    val name: String? = "Kotlin"

    if (name != null) {
        println("Length: ${name.length}")
    } else {
        println("Name is unavailable.")
    }
}

Output

Length: 6

Inside the first branch, name is known to be non-null, so its length property can be accessed without the safe-call operator.

Nested If-Else Statements in Kotlin

We can nest an if-else statement inside another if-else statement. When we say if-else in this context, it could be simple if statement, or if-else statement or if-else-if statement.

In the following example, we have written an if-else-if statement inside a simple if statement.

Main.kt

</>
Copy
fun main(args: Array<String>) {
    val a = 6

    if(a%2==0) {
        println("$a is even number.")
        if(a%5==0) {
            println("$a is divisible by 5.")
        } else if(a%3==0) {
            println("$a is divisible by 3.")
        }
    }
}

Run the program.

Output

6 is even number.
6 is divisible by 3.

if-else-if statement inside if statement is like any other Kotlin statement. So, the if the execution enters inside the if statement, if-else-if shall be executed like we have seen in the previous examples.

Nested conditions are useful when the inner decision is relevant only after the outer condition succeeds. For many unrelated alternatives, an else if ladder or a Kotlin when expression is often easier to read.

Kotlin If-Else versus When Expression

Use if-else for Boolean decisions, ranges of values, or a small number of conditions. A when expression can be clearer when one value is compared against many alternatives or when a long else-if ladder becomes difficult to scan.

</>
Copy
fun main() {
    val day = 2

    val dayName = when (day) {
        1 -> "Monday"
        2 -> "Tuesday"
        3 -> "Wednesday"
        else -> "Unknown"
    }

    println(dayName)
}

Output

Tuesday

Both if and when can return values. Choose the construct that states the decision most clearly.

Common Kotlin If-Else Mistakes

  • Using = when a comparison requires ==. The operator = assigns a value, while == checks structural equality.
  • Writing a non-Boolean condition such as if (number). Kotlin requires an explicit Boolean expression such as if (number != 0).
  • Ordering broad else-if conditions before narrower conditions, making later branches unreachable for matching values.
  • Omitting else when an if expression must produce a value for every possible path.
  • Removing braces from branches that are likely to gain additional statements, which can make later edits misleading.
  • Creating deeply nested if-else statements when guard clauses, helper functions, or a when expression would be clearer.

Kotlin If-Else FAQs

Is if a statement or an expression in Kotlin?

Kotlin if can control which block runs and can also return a value. For example, val maximum = if (a > b) a else b assigns the result of the selected branch.

Does Kotlin have a ternary operator?

No. Kotlin does not use the condition ? first : second operator. Use an if-else expression such as if (condition) first else second.

Must a Kotlin if condition return Boolean?

Yes. The condition must have the type Boolean. Kotlin does not automatically convert integers, strings, or nullable references to Boolean values.

When should I use when instead of if-else in Kotlin?

Use when when one value is matched against several alternatives or when a long else-if chain becomes difficult to read. Use if-else for direct Boolean conditions and a small number of branches.

Kotlin If-Else Summary

Concluding this Kotlin Tutorial, we learned what if-else statement is and its variations in Kotlin programming language.

A Kotlin if-else construct selects a branch using a Boolean condition. It can also return a value, replace a ternary expression, form an else-if ladder, combine logical conditions, and perform null checks. For decisions with many alternatives based on one value, consider using a when expression.