英文:
Non-Exhaustive Error in When-Expression for a Sealed Class
问题
我对在使用带有 when 块的密封类时出现非穷尽错误感到震惊。
这是我正在处理的代码:
sealed class Vehicle
data class Car(val manufacturer: String, val model: String) : Vehicle()
data class Bicycle(val manufacturer: String) : Vehicle()
fun getVehicle(vehicle: Vehicle) =
when (vehicle) {
is Car -> "${vehicle.manufacturer} - ${vehicle.model}"
is Bicycle -> vehicle.manufacturer
//错误
//'when' 表达式必须是穷尽的,请添加必要的 'else' 分支
}
这是我收到的错误。
我已经与最新的 V1.8.22 文档 进行了反复核对,其中明确说明了以下内容:
如果
when
用作表达式,else
分支是必需的,除非编译器可以证明所有可能的情况都通过分支条件涵盖,例如枚举类条目和密封类子类型。
我认为密封类的所有直接子类在编译时都是已知的,因此在 when 表达式上的所有可能结果都已经考虑到了。
添加 else
块并不是什么大问题,但这对我来说有点意外。感谢您的理解。
英文:
I'm so stunned that I am getting a Non-Exhaustive Error when using a sealed classes with when-block.
This is the code that I am working with:
sealed class Vehicle
data class Car(val manufacturer: String, val model: String
) : Vehicle()
data class Bicycle(
val manufacturer: String
) : Vehicle()
fun getVehicle(vehicle: Vehicle) =
when (vehicle) {
is Car -> "${vehicle.manufacturer} - ${vehicle.model}"
is Bicycle -> vehicle.manufacturer
//Error
//'when' expression must be exhaustive, add necessary 'else' branch
}
This is the error I am getting.
I have counter-checked with the latest V1.8.22 docs which clearly state the following:
> if when is used as an expression, the else branch is mandatory, unless
> the compiler can prove that all possible cases are covered with branch
> conditions, for example, with enum class entries and sealed class
> subtypes).
I am of the view that all direct subclasses of a sealed class are known at the compile time and thus all outcomes on the when-expression are accounted for.
It is not a big deal to add the else-block
but this comes as a shocker to me. I will appreciate your understanding on this.
答案1
得分: 3
代码按您发布的方式编译时没有错误。可能您在某处还有另一个“Vehicle”子类。您可以通过选择“Vehicle”并使用层次结构视图(我设置为Ctrl-H)或选择“when”,然后按Alt-Enter -> 添加剩余分支来找到它。
英文:
The code as you posted it compiles without errors. You probably have another Vehicle
subclass floating around somewhere. You can find it either by selecting Vehicle and using the Hierarchy view (Ctrl-H on my setup) or by selecting the when
and pressing Alt-Enter -> Add remaining branches.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论