Sobes.tech
Junior — Middle

Kas saaksite selgitada 'when' operaatori tööpõhimõtet Kotlin keeles?

sobes.tech AI

Vastus AI-lt

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

Principle of operation:

  • The expression after when is evaluated.
  • The value is compared with each specified option (branch).
  • If a match is found, the corresponding code block is executed.
  • If no options match, 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 can be used in ranges (in), types (is), or arbitrary conditions.
  • when can be used as an expression returning a value.

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