When expression must be exhaustive in all cases


#1

Here is a piece of code
override fun onOptionsItemSelected(item: MenuItem) { when (item.itemId) { R.id.action_settings -> consume { navigateToSettings() } R.id.nav_camera -> drawer.consume { navigateToCamera() } R.id.nav_gallery -> drawer.consume { loadGallery() } R.id.nav_slideshow -> drawer.consume { loadSlideshow() } } }

It can be changed to the following code with inferred return type

override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.action_settings -> consume { navigateToSettings() } R.id.nav_camera -> drawer.consume { navigateToCamera() } R.id.nav_gallery -> drawer.consume { loadGallery() } R.id.nav_slideshow -> drawer.consume { loadSlideshow() } }

Although in this case the compiler mentions that "when expression must be exhaustive add necessary else branch"
I added the line below and the error wen away
else -> super.onOptionsItemSelected(item)

Shouldn’t we have the same behaviour in both cases for more consistency?


#2

Your first snippet doesn’t return anything (well, Unit), that’s the reason it doesn’t have to be exhaustive. When you return the value of the when expression it needs to have a value for every case.


#3

Oh I see thanks for clarifying that :wink: