Kotlin If Else Statement

The Kotlin if statement is a conditional control structure that executes a block of code only when a specified condition evaluates to true. Unlike many other programming languages, Kotlin if statements can function both as statements (performing actions) and as expressions (returning values).

val userAge = 25  
  
if (userAge >= 18) {  
    println("User is eligible for adult content")  
}  

In this example, the if statement checks whether the user’s age meets the minimum requirement. The condition userAge >= 18 must evaluate to a boolean value (true or false).

Kotlin If Else Syntax Structure

The basic Kotlin if else syntax follows this pattern:

if (condition) {  
    // Code executed when condition is true  
} else {  
    // Code executed when condition is false  
}  

The condition must be a boolean expression. When the condition is true, the if block executes; when false, the else block executes. Only one block will ever execute in a single if-else evaluation.

Boolean Conditions in Kotlin

Kotlin if else statements rely on boolean conditions created using comparison operators:

  • == (equal to)
  • != (not equal to)
  • > (greater than)
  • < (less than)
  • >= (greater than or equal to)
  • <= (less than or equal to)
val temperature = 32  
val humidity = 75  
  
if (temperature > 30 && humidity > 70) {  
    println("Weather is hot and humid")  
} else {  
    println("Weather conditions are moderate")  
}  

Kotlin If Else Expression: The Power of Returning Values

If Else as Expression vs Statement

One of Kotlin’s most powerful features is treating if else as an expression. Unlike traditional statements that just execute code, expressions return values that can be assigned to variables or used in calculations.

val userRole = "admin"  
  
// Traditional statement approach  
var accessLevel: String  
if (userRole == "admin") {  
    accessLevel = "full"  
} else {  
    accessLevel = "limited"  
}  
  
// Expression approach (preferred in Kotlin)  
val accessLevel = if (userRole == "admin") "full" else "limited"  

The expression approach is more concise and functional, eliminating the need for mutable variables.

Mandatory Else in Expressions

When using Kotlin if as expression, the else branch becomes mandatory. This ensures that the expression always returns a value, preventing potential runtime errors.

val score = 85  
  
// This works - complete expression with else  
val grade = if (score >= 90) "A" else "B"  
  
// This would cause compilation error - missing else  
// val grade = if (score >= 90) "A"  

Multi-line If Else Expressions

Kotlin if else expressions can contain multiple statements in each branch. The last expression in each block becomes the returned value.

val gameScore = 2500  
val playerLevel = if (gameScore > 2000) {  
    println("Calculating advanced level...")  
    val baseLevel = gameScore / 1000  
    val bonusPoints = gameScore % 1000  
    baseLevel + (bonusPoints / 100)  // This value is returned  
} else {  
    println("Calculating beginner level...")  
    gameScore / 500  // This value is returned  
}  

Advanced Kotlin Conditional Statements

If Else If Ladder

For handling multiple conditions, Kotlin if else if statements create a ladder-like structure where conditions are evaluated sequentially until one matches.

val batteryLevel = 45  
  
val batteryStatus = if (batteryLevel >= 80) {  
    "Excellent"  
} else if (batteryLevel >= 60) {  
    "Good"  
} else if (batteryLevel >= 40) {  
    "Fair"  
} else if (batteryLevel >= 20) {  
    "Low"  
} else {  
    "Critical"  
}  
  
println("Battery status: $batteryStatus")  

Each condition is checked in order. Once a condition evaluates to true, that block executes and the remaining conditions are skipped.

Nested If Statements

Nested if statements in Kotlin allow you to place if conditions inside other if blocks, creating complex decision trees for sophisticated logic.

val userType = "premium"  
val subscriptionActive = true  
val paymentCurrent = true  
  
if (userType == "premium") {  
    if (subscriptionActive) {  
        if (paymentCurrent) {  
            println("Access granted to all premium features")  
        } else {  
            println("Please update payment method")  
        }  
    } else {  
        println("Please renew your subscription")  
    }  
} else {  
    println("Upgrade to premium for full access")  
}  

While powerful, excessive nesting can reduce code readability. Consider refactoring deeply nested conditions into separate functions or using when expressions for better maintainability.

Logical Operators in Conditions

Kotlin supports logical operators to combine multiple conditions:

  • && (logical AND)
  • || (logical OR)
  • ! (logical NOT)
val age = 25  
val hasLicense = true  
val hasInsurance = true  
  
if (age >= 18 && hasLicense && hasInsurance) {  
    println("Eligible to drive")  
} else if (age >= 18 && hasLicense && !hasInsurance) {  
    println("Need insurance to drive legally")  
} else if (age >= 18 && !hasLicense) {  
    println("Need to obtain a driving license")  
} else {  
    println("Too young to drive")  
}  

Kotlin When Expression: Alternative to If Else

When vs If Else

For multiple condition checks, Kotlin when expression often provides cleaner syntax than lengthy if-else-if chains. When expressions are particularly useful for matching against multiple values or ranges.

val dayOfWeek = 3  
  
// Using if-else-if  
val dayType = if (dayOfWeek == 1 || dayOfWeek == 7) {  
    "Weekend"  
} else if (dayOfWeek in 2..6) {  
    "Weekday"  
} else {  
    "Invalid day"  
}  
  
// Using when (cleaner)  
val dayType = when (dayOfWeek) {  
    1, 7 -> "Weekend"  
    in 2..6 -> "Weekday"  
    else -> "Invalid day"  
}  

When with Ranges and Collections

When expressions excel at checking ranges and collection membership:

val studentGrade = 'B'  
  
val description = when (studentGrade) {  
    'A' -> "Excellent performance"  
    'B' -> "Good performance"   
    'C' -> "Average performance"  
    in 'D'..'F' -> "Needs improvement"  
    else -> "Invalid grade"  
}  

Practical Examples and Use Cases

User Authentication Logic

fun authenticateUser(username: String, password: String, isActive: Boolean): String {  
    return if (username.isNotEmpty() && password.length >= 8) {  
        if (isActive) {  
            "Authentication successful"  
        } else {  
            "Account is deactivated"  
        }  
    } else {  
        "Invalid credentials"  
    }  
}  

Mobile App Permission Checking

fun checkAppPermissions(hasCamera: Boolean, hasLocation: Boolean, hasStorage: Boolean): String {  
    val permissionCount = listOf(hasCamera, hasLocation, hasStorage).count { it }  
      
    return if (permissionCount == 3) {  
        "All permissions granted - full functionality available"  
    } else if (permissionCount >= 2) {  
        "Most permissions granted - limited functionality"  
    } else if (permissionCount == 1) {  
        "Minimal permissions - basic functionality only"  
    } else {  
        "No permissions granted - app functionality restricted"  
    }  
}  

E-commerce Discount Calculator

fun calculateDiscount(totalAmount: Double, customerType: String, isFirstPurchase: Boolean): Double {  
    val baseDiscount = if (customerType == "premium") {  
        0.15  
    } else if (customerType == "regular") {  
        0.10  
    } else {  
        0.05  
    }  
      
    val finalDiscount = if (isFirstPurchase) {  
        baseDiscount + 0.05  // Additional 5% for first purchase  
    } else {  
        baseDiscount  
    }  
      
    return totalAmount * (1 - finalDiscount)  
}  

Complete Working Examples

Example 1: Student Grade Calculator

import kotlin.random.Random  
  
fun main() {  
    // Sample student data  
    val students = listOf(  
        Student("Alice", 92),  
        Student("Bob", 78),  
        Student("Charlie", 85),  
        Student("Diana", 67),  
        Student("Eve", 94)  
    )  
      
    println("=== Student Grade Report ===")  
    students.forEach { student ->  
        val grade = calculateGrade(student.score)  
        val status = if (student.score >= 70) "PASS" else "FAIL"  
        val recommendation = getRecommendation(student.score)  
          
        println("Student: ${student.name}")  
        println("Score: ${student.score}")  
        println("Grade: $grade")  
        println("Status: $status")  
        println("Recommendation: $recommendation")  
        println("---")  
    }  
}  
  
data class Student(val name: String, val score: Int)  
  
fun calculateGrade(score: Int): String {  
    return if (score >= 90) {  
        "A+"  
    } else if (score >= 85) {  
        "A"  
    } else if (score >= 80) {  
        "B+"  
    } else if (score >= 75) {  
        "B"  
    } else if (score >= 70) {  
        "C+"  
    } else if (score >= 65) {  
        "C"  
    } else if (score >= 60) {  
        "D"  
    } else {  
        "F"  
    }  
}  
  
fun getRecommendation(score: Int): String {  
    return if (score >= 90) {  
        "Excellent work! Consider advanced courses."  
    } else if (score >= 80) {  
        "Good performance! Keep up the effort."  
    } else if (score >= 70) {  
        "Satisfactory. Focus on weak areas."  
    } else if (score >= 60) {  
        "Additional study required."  
    } else {  
        "Needs significant improvement. Consider tutoring."  
    }  
}  

Output:

=== Student Grade Report ===  
Student: Alice  
Score: 92  
Grade: A+  
Status: PASS  
Recommendation: Excellent work! Consider advanced courses.  
---  
Student: Bob  
Score: 78  
Grade: B  
Status: PASS  
Recommendation: Good performance! Keep up the effort.  
---  
Student: Charlie  
Score: 85  
Grade: A  
Status: PASS  
Recommendation: Good performance! Keep up the effort.  
---  
Student: Diana  
Score: 67  
Grade: C  
Status: FAIL  
Recommendation: Additional study required.  
---  
Student: Eve  
Score: 94  
Grade: A+  
Status: PASS  
Recommendation: Excellent work! Consider advanced courses.  
---  

Example 2: Banking Transaction Processor

import java.time.LocalDateTime  
import java.time.format.DateTimeFormatter  
  
fun main() {  
    val account = BankAccount("ACC123456", 1500.0)  
      
    // Process various transactions  
    val transactions = listOf(  
        Transaction("DEPOSIT", 500.0),  
        Transaction("WITHDRAWAL", 200.0),  
        Transaction("WITHDRAWAL", 2000.0), // Should fail  
        Transaction("TRANSFER", 300.0),  
        Transaction("DEPOSIT", 1000.0)  
    )  
      
    println("=== Banking Transaction Processor ===")  
    println("Initial Balance: $${account.balance}")  
    println("Account: ${account.accountNumber}")  
    println()  
      
    transactions.forEach { transaction ->  
        val result = processTransaction(account, transaction)  
        println("Transaction: ${transaction.type} - $${transaction.amount}")  
        println("Result: $result")  
        println("New Balance: $${account.balance}")  
        println("---")  
    }  
      
    // Generate account summary  
    val summary = generateAccountSummary(account)  
    println(summary)  
}  
  
data class BankAccount(val accountNumber: String, var balance: Double)  
data class Transaction(val type: String, val amount: Double)  
  
fun processTransaction(account: BankAccount, transaction: Transaction): String {  
    val timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))  
      
    return if (transaction.amount <= 0) {  
        "FAILED: Invalid amount. Amount must be positive."  
    } else if (transaction.type == "WITHDRAWAL" || transaction.type == "TRANSFER") {  
        if (account.balance >= transaction.amount) {  
            account.balance -= transaction.amount  
            "SUCCESS: ${transaction.type} processed at $timestamp"  
        } else {  
            "FAILED: Insufficient funds. Available: $${account.balance}"  
        }  
    } else if (transaction.type == "DEPOSIT") {  
        account.balance += transaction.amount  
        "SUCCESS: DEPOSIT processed at $timestamp"  
    } else {  
        "FAILED: Unknown transaction type: ${transaction.type}"  
    }  
}  
  
fun generateAccountSummary(account: BankAccount): String {  
    val status = if (account.balance >= 1000) {  
        "PREMIUM"  
    } else if (account.balance >= 500) {  
        "STANDARD"  
    } else if (account.balance >= 100) {  
        "BASIC"  
    } else {  
        "MINIMUM"  
    }  
      
    val creditLimit = if (status == "PREMIUM") {  
        account.balance * 0.5  
    } else if (status == "STANDARD") {  
        account.balance * 0.3  
    } else {  
        0.0  
    }  
      
    return """  
        === Account Summary ===  
        Account: ${account.accountNumber}  
        Current Balance: $${account.balance}  
        Account Status: $status  
        Available Credit: $${creditLimit}  
        Account Health: ${if (account.balance > 0) "HEALTHY" else "OVERDRAWN"}  
    """.trimIndent()  
}  

Output:

=== Banking Transaction Processor ===  
Initial Balance: $1500.0  
Account: ACC123456  
  
Transaction: DEPOSIT - $500.0  
Result: SUCCESS: DEPOSIT processed at 2025-06-13 14:30:25  
New Balance: $2000.0  
---  
Transaction: WITHDRAWAL - $200.0  
Result: SUCCESS: WITHDRAWAL processed at 2025-06-13 14:30:25  
New Balance: $1800.0  
---  
Transaction: WITHDRAWAL - $2000.0  
Result: FAILED: Insufficient funds. Available: $1800.0  
New Balance: $1800.0  
---  
Transaction: TRANSFER - $300.0  
Result: SUCCESS: TRANSFER processed at 2025-06-13 14:30:25  
New Balance: $1500.0  
---  
Transaction: DEPOSIT - $1000.0  
Result: SUCCESS: DEPOSIT processed at 2025-06-13 14:30:25  
New Balance: $2500.0  
---  
  
=== Account Summary ===  
Account: ACC123456  
Current Balance: $2500.0  
Account Status: PREMIUM  
Available Credit: $1250.0  
Account Health: HEALTHY  

Example 3: Mobile App Settings Manager

import kotlin.random.Random  
  
fun main() {  
    val settingsManager = AppSettingsManager()  
      
    // Simulate various user actions  
    println("=== Mobile App Settings Manager ===")  
      
    // Check notification permissions  
    val notificationAccess = checkNotificationPermission(Random.nextBoolean())  
    println("Notification Permission: $notificationAccess")  
      
    // Handle theme settings  
    val themes = listOf("light", "dark", "auto", "custom")  
    themes.forEach { theme ->  
        val themeResult = settingsManager.setTheme(theme)  
        println("Theme '$theme': $themeResult")  
    }  
      
    println()  
      
    // Test privacy settings  
    val privacyLevels = listOf("public", "friends", "private", "custom")  
    privacyLevels.forEach { level ->  
        val privacyResult = settingsManager.setPrivacyLevel(level)  
        println("Privacy '$level': $privacyResult")  
    }  
      
    println()  
      
    // Generate settings summary  
    val summary = settingsManager.generateSettingsSummary()  
    println(summary)  
}  
  
class AppSettingsManager {  
    private var currentTheme = "light"  
    private var privacyLevel = "friends"  
    private var notificationsEnabled = true  
    private var locationEnabled = false  
      
    fun setTheme(theme: String): String {  
        return if (theme == "light" || theme == "dark") {  
            currentTheme = theme  
            "Theme set to $theme mode successfully"  
        } else if (theme == "auto") {  
            currentTheme = theme  
            "Auto theme enabled - will follow system settings"  
        } else if (theme == "custom") {  
            currentTheme = theme  
            "Custom theme enabled - user preferences applied"  
        } else {  
            "Invalid theme option. Available: light, dark, auto, custom"  
        }  
    }  
      
    fun setPrivacyLevel(level: String): String {  
        return if (level == "public") {  
            privacyLevel = level  
            "Privacy set to public - profile visible to everyone"  
        } else if (level == "friends") {  
            privacyLevel = level  
            "Privacy set to friends only - limited visibility"  
        } else if (level == "private") {  
            privacyLevel = level  
            "Privacy set to private - maximum protection"  
        } else if (level == "custom") {  
            privacyLevel = level  
            "Custom privacy settings applied"  
        } else {  
            "Invalid privacy level. Available: public, friends, private, custom"  
        }  
    }  
      
    fun generateSettingsSummary(): String {  
        val securityScore = if (privacyLevel == "private") {  
            100  
        } else if (privacyLevel == "friends") {  
            70  
        } else if (privacyLevel == "custom") {  
            80  
        } else {  
            40  
        }  
          
        val accessibilityFeatures = if (currentTheme == "dark") {  
            "Enhanced for low-light viewing"  
        } else if (currentTheme == "auto") {  
            "Adaptive display based on time"  
        } else {  
            "Standard display settings"  
        }  
          
        return """  
            === Settings Summary ===  
            Current Theme: $currentTheme  
            Privacy Level: $privacyLevel  
            Security Score: $securityScore/100  
            Accessibility: $accessibilityFeatures  
            Notifications: ${if (notificationsEnabled) "Enabled" else "Disabled"}  
            Recommendation: ${getRecommendation(securityScore)}  
        """.trimIndent()  
    }  
      
    private fun getRecommendation(score: Int): String {  
        return if (score >= 90) {  
            "Excellent security configuration!"  
        } else if (score >= 70) {  
            "Good security settings. Consider private mode for better protection."  
        } else if (score >= 50) {  
            "Moderate security. Review privacy settings."  
        } else {  
            "Low security score. Enable private mode and review permissions."  
        }  
    }  
}  
  
fun checkNotificationPermission(hasPermission: Boolean): String {  
    return if (hasPermission) {  
        "Granted - App can send notifications"  
    } else {  
        "Denied - Please enable in system settings for full functionality"  
    }  
}  

Output:

=== Mobile App Settings Manager ===  
Notification Permission: Granted - App can send notifications  
  
Theme 'light': Theme set to light mode successfully  
Theme 'dark': Theme set to dark mode successfully  
Theme 'auto': Auto theme enabled - will follow system settings  
Theme 'custom': Custom theme enabled - user preferences applied  
  
Privacy 'public': Privacy set to public - profile visible to everyone  
Privacy 'friends': Privacy set to friends only - limited visibility  
Privacy 'private': Privacy set to private - maximum protection  
Privacy 'custom': Custom privacy settings applied  
  
=== Settings Summary ===  
Current Theme: custom  
Privacy Level: custom  
Security Score: 80/100  
Accessibility: Standard display settings  
Notifications: Enabled  
Recommendation: Good security settings. Consider private mode for better protection.  

Key Takeaways for Kotlin If Else Mastery

Understanding Kotlin if else statements is crucial for effective Android development and Kotlin programming. The unique expression-based approach of Kotlin conditional statements offers more flexibility and functional programming benefits compared to traditional imperative languages.

Remember these essential points:

  1. Kotlin if else can function as both statements and expressions

  2. When using if as expression, the else branch is mandatory

  3. Nested if statements should be used judiciously to maintain code readability

  4. When expressions often provide cleaner alternatives to complex if-else-if chains

  5. Logical operators (&&, ||, !) enable sophisticated condition combinations