when must be exhaustive kotlin ?
- Street: Zone Z
- City: forum
- State: Florida
- Country: Afghanistan
- Zip/Postal Code: Commune
- Listed: 2 November 2022 5 h 36 min
- Expires: This ad has expired
Description
when must be exhaustive kotlin ?
### When Does a `when` Expression in Kotlin Need to Be Exhaustive?
In the Kotlin programming language, understanding when a `when` expression must be exhaustive can sometimes be a point of confusion. The `when` expression is a powerful tool that serves as both a switch statement (a statement that controls the flow of execution based on multiple conditions) and an expression returning a value. But when does it have to cover every possible case, and when can you leave some out?
#### Understanding Exhaustiveness
In Kotlin, `when` is exhaustive when it lists out all possible branches or defaults to an `else` block to handle cases not explicitly covered by the individual branches. The necessity for an exhaustive `when` expression varies based on the context of its usage.
##### Enums and Sealed Classes
If your `when` expression is iterating over an `enum`, `sealed class` or any other type with a known and finite number of instances, Kotlin will require you to make the `when` expression exhaustive. Your `when` block must cover all instances of that type, or provide a `else` branch to catch any remaining cases. This is a valuable safety feature, allowing the compiler to ensure nothing is missed, which can eliminate hard-to-find bugs.
For instance, let’s consider an enumeration for `Planets`. Your `when` statement would need to account for each planet, or provide an `else` case to handle unexpected values:
“`kotlin
fun planetData(planet: Planet): String {
return when (planet) {
Planets.MERCURY, Planets.VENUS -> “Terrestrial planet”
Planets.EARTH -> “The blue planet”
Planets.MARS -> “The red planet”
Planets.JUPITER, Planets.SATURN, Planets.URANUS, Planets.NEPTUNE,
Planets.PLUTO -> “Not a terrestrial planet”
}
}
“`
This code snipped would produce a compilation error since it does not cover all enum values. You would need to add a pattern or an `else` case to ensure that all possibilities are handled, making the `when` expression exhaustive.
##### When an `else` is Implicit
When using `when` as a statement, it does not necessarily need to be exhaustive. An `else` case would still be useful to catch any unexpected cases but it’s not strictly required. For example:
“`kotlin
fun handlePlanet(planet: Planet) {
when (planet) {
Planets.MERCURY, Planets.VENUS -> println(“This is a terrestrial planet”)
Planets.EARTH -> println(“This is Earth”)
Planets.MARS -> println(“This is Mars”)
}
}
“`
In this scenario, the function `handlePlanet(planet)` is used as a statement, which means the `when` block may or may not exhaustively handle all possible values of `planet`.
##### Context Determines Exhaustiveness
It’s worth noting that the determination to require exhaustiveness originates from the context in which the `when` expression is being used:
– **As an expression:** If the `when` is an expression—that is, if its value is used or returned somewhere—then it must be exhaustive to ensure that all possible values of the evaluated variable are accounted for. It’s not okay to miss any case since your program might crash or yield incorrect results if it encounters a case you did not plan for.
– **As a statement:** If `when` is being used as a statement to execute each branch without returning a value, the compiler will not force you to make it exhaustive. However, including a catch-all `else` case can serve as a safeguard against programming errors or unexpected input.
#### Where to Go from Here
If the exhaustiveness requirement is causing problems or the else branch is unreachable and you’re sure you’ve covered all possible cases, you can use `else` and throw an exception. This provides a fallback or a safeguard to ensure that the program can handle the case where you might have missed a scenario:
“`kotlin
when (type) {
Type.A, Type.B -> println(“Cases A or B”)
else -> throw IllegalStateException(“Unexpected value: $type”)
}
“`
This approach prevents runtime errors. You’re telling the Kotlin compiler “Under all normal circumstances, these are the only cases that can occur.”
#### Next Steps
For more detailed exploration and practical examples on this topic, I would recommend taking a look at these resources:
– [Kotlin – When Statements (Exhaustiveness Enforcement)](https://proandroiddev.com › til-when-is-when-exhaustive-31d69f630a8b)
– [Guide to When Expression](https://www.geeksforgeeks.org › kotlin-when-expression)
Understanding when a `when` expression must be exhaustive is key to avoiding runtime bugs and ensuring your Kotlin programs are robust. It is a feature that enhances your code’s clarity and integrity, helping to avoid situations where cases are missed or assumed incorrectly. So next time you’re coding in Kotlin, give some thought to whether your `when` expression is truly exhaustive, and the implications of exhaustive vs. non-exhaustive in your specific use case.
278 total views, 1 today
Recent Comments