Tobias Reich
Tobias Reich

Reputation: 5160

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?

Upvotes: 4

Views: 1439

Answers (2)

voddan
voddan

Reputation: 33749

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.

Upvotes: 2

Gal Naor
Gal Naor

Reputation: 2397

You can achieve that by using sealed classes.

You can migrate your enum to sealed class, and use it like this:

sealed class MyFancyEnum {
   object TYPE_A : MyFancyEnum()
   object TYPE_B : MyFancyEnum()
   object TYPE_C : MyFancyEnum()
}

fun setFancyEnum(fancyEnum: MyFancyEnum) {
   when(fancyEnum) {
     is MyFancyEnum.TYPE_A -> ...
     is MyFancyEnum.TYPE_B -> ...    
  }
}

In that case, it won't even compile, because not all sealed class options are handled.

Upvotes: 0

Related Questions