非尽错误在密封类的 When 表达式中

huangapple go评论56阅读模式
英文:

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.

非尽错误在密封类的 When 表达式中

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.

huangapple
  • 本文由 发表于 2023年6月29日 13:54:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76578370.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定