Kotlin If...Else

Kotlin If...Else Statements

Kotlin supports the usual logical conditions from mathematics. You can use these conditions to perform different actions for different decisions.


The if..else Statement

Example

fun main() {
  val time = 20
  if (time < 18) {
    println("Good day.")
  } else {
    println("Good evening.")
  }
}

Kotlin if..else as an Expression

In Kotlin, if can also be used as an expression (it returns a value). This allows you to assign the result of an if-statement directly to a variable.

If Expression Example

fun main() {
  val time = 20
  val greeting = if (time < 18) "Good day." else "Good evening."
  println(greeting)
}

Note: When using if as an expression, it must have an else branch.