Search code examples
kotlinsealed-class

Force compiler to emit an error when not all implementations are covered in "when" statement


Maybe this is an absurd question. I have a method that receives a Command (sealed class) and returns Unit and I want the compiler to crash whether all the when branches have not been implemented:

sealed class Command
class FirstCommand : Command()
class SecondCommand: Command()

fun handle(cmd: Command) {
  when(cmd) {
    is FirstCommand -> //whatever     
  }
}

The code above is ok, but I would like it not to compile.

When method returns anything different from Unit, it does not compile:

fun handle(cmd: Command) : Any {
  when(cmd) { //error, when must be exhaustive and requires all branches
    is FirstCommand -> //whatever     
  }
}

I want that behavior but returning nothing (Unit). I understand why that happens, but I'm wondering if there is any way I can change my code to achieve what I want. I need cover all the Command implementations without forget anyone that may be added later.


Solution

  • Solved. I didn't know you can use return statement even when method returns Unit:

    fun handle(cmd: Command) {
      return when(cmd) {
        is FirstCommand -> //whatever     
      }
    }
    

    Now, code above does not compile because when needs all the branches. Just what I wanted.