Kotlin when statement is same as Java’s Switch statement. When statement in Kotlin allows a variable to be tested for equality against a list of values.
If none of the branch conditions are satisfied it will return the value of else branch.
For when statement it is not mandatory to use expression.In the above example, first program we used when as an expression. However, in the second operator enter it’s is not using an expression. Refer the above program for more understanding.
Kotlin Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
fun main(args: Array<String>) { val value1 = 90 val value2 = 6 println("Enter operator either +, -, * or /") var operator = readLine() val result = when (operator) { "+" -> value1 + value2 "-" -> value1 - value2 "*" -> value1 * value2 "/" -> value1 / value2 else -> "$operator operator is invalid operator." } println("result = $result") val a = 100 val b = 6 println("Enter operator either +, -, * or /") operator = readLine() when (operator) { "+" -> println("$a + $b = ${a + b}") "-" -> println("$a - $b = ${a - b}") "*" -> println("$a * $b = ${a * b}") "/" -> println("$a / $b = ${a / b}") else -> println("$operator is invalid") } } |
Output:
1 2 3 4 5 6 7 8 |
Enter operator either +, -, * or / / result = 15 Enter operator either +, -, * or / * 100 * 6 = 600 |