简体   繁体   English

意外的奇怪错误 Kotlin “密封” class 与“何时”一起使用

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

I have come across a very weird error - kotlin sealed class with when .我遇到了一个非常奇怪的错误 - kotlin 用 when 密封 class

this my Sealed class这是我的密封 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这是我当 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 'when' 表达式必须是详尽的,添加必要的 'null' 分支或 'else' 分支

You might say, the error is obvious, just add a else branch.您可能会说,错误很明显,只需添加一个else分支。 But it seems to be wrong, because, in sealed class, there will not be other case, that is else branch should never exucute.但这似乎是错误的,因为在密封的 class 中,不会有其他情况,即else分支永远不应该执行。 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.如果可以验证语句涵盖所有情况,则无需在语句中添加 else 子句。

adding else branch will work, the error disappears.添加 else 分支将起作用,错误消失。 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似乎resource可以为空,这就是编译器需要添加'null' branch or 'else' branch的原因

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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