Sobes.tech
Junior — Middle

Can you explain how the 'when' operator works in Kotlin?

sobes.tech AI

Answer from AI

The when operator in Kotlin is an extended version of the switch operator from other languages. It is used to select one of several code execution options depending on the value of an expression.

Working principle:

  • The expression after when is evaluated.
  • The value is compared with each specified branch.
  • If a match is found, the corresponding block of code is executed.
  • If no match is found, the else block is executed, if present.

Example:

val x = 3
when (x) {
    1 -> println("One")
    2 -> println("Two")
    3, 4 -> println("Three or four")
    in 5..10 -> println("From five to ten")
    else -> println("Other number")
}

Features:

  • Branches can contain multiple values separated by commas.
  • Checks in ranges (in), types (is), or arbitrary conditions can be used.
  • when can be used as an expression, returning a value.

This makes when very flexible and convenient for controlling the flow of execution.

Can you explain how the 'when' operator works in… - sobes.tech