Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Kotlin if-else expression

In Kotlin, control flow structures like if-else are expressions, meaning they can return a value. This is a significant departure from many traditional programming languages and allows for more concise and expressive code.

Here's a tutorial on the if-else expression in Kotlin:

1. Basic if-else:

Just like in many languages, the if-else structure can be used without returning a value.

val number = 10

if (number > 5) {
    println("Number is greater than 5")
} else {
    println("Number is less than or equal to 5")
}

2. If as an Expression:

The ability to return a value from an if-else expression allows you to assign the result directly to a variable.

val number = 10
val result = if (number > 5) "Greater" else "Lesser"
println(result)  // Prints: Greater

3. Multiple Conditions:

You can add as many else if clauses as necessary:

val score = 85
val grade = if (score >= 90) {
    "A"
} else if (score >= 80) {
    "B"
} else if (score >= 70) {
    "C"
} else {
    "D"
}
println(grade)  // Prints: B

4. If as an Expression with Block:

If you have multiple statements in the block of your if or else, the last expression in the block is what gets returned.

val number = 7
val result = if (number % 2 == 0) {
    println("Even number")
    "Even"
} else {
    println("Odd number")
    "Odd"
}
println(result)  // Prints: Odd number followed by Odd

5. Omitting the else clause:

When you omit the else clause in an if expression, the omitted branch will return the special value Unit (similar to void in other languages).

val number = 5
val isEven = if (number % 2 == 0) true else Unit
println(isEven)  // Prints: kotlin.Unit

6. Nested if-else:

if-else expressions can be nested for more complex conditions.

val number = 15

val result = if (number > 0) {
    if (number % 2 == 0) {
        "Positive Even"
    } else {
        "Positive Odd"
    }
} else if (number == 0) {
    "Zero"
} else {
    "Negative"
}
println(result)  // Prints: Positive Odd

Conclusion:

The if-else expression in Kotlin provides a powerful and concise way to handle conditional logic. By being able to return values, it simplifies many scenarios where you would traditionally use a ternary conditional operator (like ? : in Java or C++). Familiarizing yourself with this concept can help streamline your Kotlin code.

  1. Conditional statements in Kotlin with if-else:

    • Basic usage of if-else statement.
    val x = 10
    if (x > 5) {
        println("x is greater than 5")
    } else {
        println("x is not greater than 5")
    }
    
  2. Single-line vs multi-line if-else in Kotlin:

    • Compare single-line and multi-line if-else.
    val result = if (x > 5) "Greater" else "Not Greater"
    
  3. Using if-else expression with assignments in Kotlin:

    • Assign values based on conditions.
    val status = if (x > 0) "Positive" else "Non-positive"
    
  4. Chaining if-else expressions in Kotlin:

    • Chain multiple conditions.
    val grade = if (score > 90) "A" else if (score > 80) "B" else "C"
    
  5. Nested if-else expressions in Kotlin:

    • Nest if-else statements.
    val category = if (x > 0) {
        if (x % 2 == 0) "Positive Even" else "Positive Odd"
    } else {
        "Non-positive"
    }
    
  6. Kotlin if-else expression vs when expression:

    • Compare if-else and when expressions.
    val result = when {
        x > 5 -> "Greater"
        x == 5 -> "Equal"
        else -> "Less"
    }
    
  7. Ternary operator equivalent in Kotlin:

    • Achieve a ternary-like effect.
    val max = if (a > b) a else b
    
  8. If-else expression with ranges in Kotlin:

    • Use ranges in conditions.
    val rangeResult = if (x in 1..10) "In range" else "Out of range"
    
  9. Equality and comparison in if-else expression in Kotlin:

    • Use == and != for equality and inequality.
    val message = if (x == 0) "Zero" else "Non-zero"
    
  10. Handling nullability with if-else expression in Kotlin:

    • Safely handle nullable values.
    val length = if (text != null) text.length else 0
    
  11. Using if-else expression in Kotlin functions:

    • Utilize if-else in functions.
    fun isPositive(num: Int): Boolean {
        return if (num > 0) true else false
    }
    
  12. Common pitfalls with if-else expressions in Kotlin:

    • Be aware of common mistakes and best practices.
    val value = if (condition) "True"  // Incorrect: Missing else part