So I have many Enums in my app which get used in kotlins when calls.
For instance my enum class
enum class MyFancyEnum {
TYPE_A,TYPE_B, TYPE_C
}
is used in something like this:
when (it){
TYPE_A -> { ... }
}
What I need is a warning (or even better an error) in case I have forgotten to distinguish between all branches.
I can see, the compiler is highlighting this already and moving the cursor on it I get a message similar to that one:
'when' expression on enum is recommended to be exhaustive, add '...' branch or 'else' branch instead
However, there are no lint checks for this in Android Studio. (One seems to be switch-case for Java but nothing similar for Kotlin).
Question: How can I get a Lint Warning / Error in case I forgot one branch in a when expression?
This is the workaround the was suggested in the comments: add an empty .also{} operator to the end of the when expression.
when (it){
TYPE_A -> { ... }
}.also{}
This trick utilises the Kotlin compiler itself, which requires all branches of when to be covered if the result of the when() { .. } expression is used by someone. Since .also{} technically uses the result of the when, this triggers a compiler error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With