when

5 0 0
                                        

syntax:

when(variableName){

     value1 -> { // statement 1 }

     value2 -> { // statement 2 }

     else -> { //statement 3}

}

when - It functions like a switch statement but just an upgrade version of switch. The variable is match to value1 first, if true, run the statement 1 but if false, check if value2 is match. If value2 is match, run the statement 2 but if false, run the else statement. But just like with if, if when is used in an expression, the last statement is the value.

syntax:

val name = when(variableName){

     value1 -> {

          // statement 1

         // last statement 1

     } value 2 ->  {

         // statement 2

        // last statement 2

      } else {

         // statement 3

         // last statement 3

      }

}

Same process will be performed. If it match with one value1, the last statement 1 is the value. If none of the values match, then the last statement 3 is the value.

Note: If each one of the possible values is covered in the matches, then you can remove the else statement.

=================

fun main(){

     println(playingWithWhen("6"))

}

fun playingWithWhen(x: Any): String{

     return when(x){

          1, 2 -> {"january to february"}

          in 3..10 -> {"march to october"}

          11 -> {"november"}

          !is Int -> {"not an integer"}

          else -> {"december"}

      }

}

================

Result:

not an integer

Note: 

1. "in" is an in-fix operator that is used in range(..) number

2. "is" is an in-fix operator that is used in checking the data type

3. you used a comma, if you have multiple values to group in one matching.

4. It is also possible that a when statement won't have a variable to compare to values. If this is the case, you can use a boolean expression in each value.

syntax:

when{

     boolean expression 1 -> { // statement 1}

     boolean expression 2 -> { //statement 2}

     else -> { // statement 3}

}

Kotlin ProgrammingWhere stories live. Discover now