Kotlin if-else: изучение условных операторов и выражений

Вот несколько методов, которые можно использовать для условных операторов (if-else) в Kotlin:

  1. Основное if-else:

    if (condition) {
    // Code to execute if the condition is true
    } else {
    // Code to execute if the condition is false
    }
  2. выражение if-else:

    val result = if (condition) {
    "Condition is true"
    } else {
    "Condition is false"
    }
  3. Вложенное if-else:

    if (condition1) {
    if (condition2) {
        // Code to execute if both conditions are true
    } else {
        // Code to execute if condition1 is true and condition2 is false
    }
    } else {
    // Code to execute if condition1 is false
    }
  4. Несколько условий с использованием else if:

    if (condition1) {
    // Code to execute if condition1 is true
    } else if (condition2) {
    // Code to execute if condition1 is false and condition2 is true
    } else {
    // Code to execute if both condition1 and condition2 are false
    }
  5. Выражение When (альтернатива переключающему регистру):

    when (value) {
    1 -> println("Value is 1")
    2 -> println("Value is 2")
    else -> println("Value is neither 1 nor 2")
    }