Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected Weird Error Kotlin "Sealed" class usage with 'when'

Tags:

android

kotlin

I have come across a very weird error - kotlin sealed class with when.

this my Sealed class

sealed class Resource<out T : Any> {
object Loading : Resource<Nothing>()
data class Success<out T : Any>(val data: T) : Resource<T>()
data class Error(val exception: Exception) : Resource<Nothing>()
data class GenericError(val errorResponse: ErrorResponse) : Resource<Nothing>()
}

this my when class

   when (resource) {
                is Resource.Loading -> {
                }
                is Resource.Error -> {
                    
                }
                is Resource.GenericError -> {
                 
                }
                is Resource.Success -> {
                   //some code - working fine
                   // additional code - weird error pops up
                }
            }

It was working fine, but I added one new line inside of one block when, compiler complains

'when' expression must be exhaustive, add necessary 'null' branch or 'else' branch instead

You might say, the error is obvious, just add a else branch. But it seems to be wrong, because, in sealed class, there will not be other case, that is else branch should never exucute. Docs also says

If it's possible to verify that the statement covers all cases, you don't need to add an else clause to the statement.

adding else branch will work, the error disappears. But I would like to know the reason behind this, why compiler suddenly pops the error, when I added additional line of code, but was working fine before.

like image 742
Azamat Mahkamov Avatar asked Oct 27 '25 06:10

Azamat Mahkamov


1 Answers

It seems that resource is nullable, that's why compiler requires to add 'null' branch or 'else' branch

like image 136
IR42 Avatar answered Oct 29 '25 20:10

IR42