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

Similar Programs Chapter Last Updated
Kotlin Continue Kotlin 02-03-2018
Kotlin Break Statement Kotlin 27-01-2018
Kotlin For Loop Kotlin 30-11-2017
Kotlin Do While Loop Kotlin 19-11-2017
Kotlin While Loop Kotlin 19-11-2017
Kotlin Nested If Kotlin 18-11-2017
Kotlin If Else If Statement Kotlin 18-11-2017
Kotlin If Statement Kotlin 17-11-2017
Kotlin Print And Println Kotlin 17-11-2017
Kotlin Type Conversion Kotlin 17-11-2017
Kotlin Logical Operators Kotlin 17-11-2017
Kotlin Assignment Operators Kotlin 15-11-2017
Kotlin Arithmetic Operators Kotlin 15-11-2017
Kotlin Data Types Kotlin 12-11-2017
Kotlin Variables Example Kotlin 11-11-2017
Kotlin Comments Example Kotlin 11-11-2017
Kotlin Hello World Kotlin 11-11-2017

1