The When expression

Kotlin provides an alternative method to the if statement—the When expression. When can also be perceived as a filter method. This is similar in nature to the Switch statement in Java or C. When sequentially matches its arguments with all branches until a condition is satisfied for a branch.

The When expression works as follows:

  • When can use arbitrary expressions and constants.
  • It takes the variable in the expression and matches the value within the branches.
  • If the condition for the variable is a match, the relevant code block of the branch will execute. If none of the other branch conditions are satisfied, the else branch is evaluated.

Writing the When statement:

  • The When statement is followed by the expression defined within the parenthesis: when (expression).
  • A branch is a condition followed by a code block. This is defined as {condition -> code block}  and appears after the expression contained within the curly brackets.
  • The else branch is mandatory with its own code block contained within the curly brackets.
  • If there is no else branch in the when, all possible cases must be covered in the branches so that the compiler can validate all of the branches.

Write a program by using when as an expression to display the day on its corresponding number, 1 for Monday, 2 for Tuesday, and so on:

fun main(args: Array<String>) {
val day = 2
when(day) {
1-> println("Monday")
2-> println("Tuesday")
3-> println("Wednesday")
4-> println("Thursday")
5-> println("Friday")
6-> println("Saturday")
7-> println("Sunday")
else -> println("Invalid input")
}
}

To verify and test various conditions, assign different values to the day variable. The program will display the respective day according to the value or error message if the input is out of range. We can rewrite the student grade program by using the when expression. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.131.10