Kotlin When Statement
Chapter:
Kotlin
Last Updated:
18-11-2017 07:13:55 UTC
Program:
/* ............... START ............... */
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")
}
}
/* ............... END ............... */
Output
Enter operator either +, -, * or /
/
result = 15
Enter operator either +, -, * or /
*
100 * 6 = 600
Notes:
-
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.
Tags
When Statement , Kotlin, When syntax in Kotlin