Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin 'when' - How to get lint warning in Android Studio

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?

like image 956
Tobias Reich Avatar asked Oct 26 '25 02:10

Tobias Reich


1 Answers

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.

like image 89
voddan Avatar answered Oct 28 '25 23:10

voddan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!