简体   繁体   中英

Unexpected Weird Error Kotlin “Sealed” class usage with 'when'

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM