The when { ... } expression

The switch { ... } control flow element is replaced by when { ... }. The when { ... } element of Kotlin is much more flexible than the switch { ... } element in Java, because it can take a value of any type. A branch only has to contain a matched condition.

The following example demonstrates how to use when { ... } as a statement:

fun whenStatement() {
val x = 1
when (x) {
1 -> println("1")
2 -> println("2")
else -> {
println("else")
}
}
}

The preceding code snippet contains the else branch, which is optional for a case with a statement. The else branch is invoked if all other branches don't have a matching condition. The else branch is mandatory if you use when { ... } as an expression and the compiler can't be sure that all possible cases are covered. The following expression returns Unit:

fun whenExpression(x: Int) = when (x) {
1 -> println("1")
2 -> println("2")
else -> {
println(x)
}
}

As you can see, expressions provide a much more concise way to write code. To be sure that your branches cover all of the possible cases, you can use enums or sealed classes.

An enum is a special kind of class that is used to define a set of constants. A sealed class is a parent class that has a restricted hierarchy of subclasses. All of the subclasses can only be defined in the same file as a sealed class.

In Kotlin, enums work similarly to how they work in Java. Sealed classes can be used if we want to restrict a class hierarchy. This works in the following way:

  1. You should declare a class using the sealed keyword
  2. All inheritors of your sealed class must be declared in the same file as their parent

The following example demonstrates how this can be implemented:

sealed class Method
class POST: Method()
class GET: Method()

With the when { ... } expression, we can use classes of the Method type, in the following way:

fun handleRequest(method: Method): String = when(method) {
is POST -> TODO("Handle POST")
is GET -> TODO("Handle GET")
}

As you can see, using this approach, we don't have to use the else branch.

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

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