假设层次 struct 为sealed
,如下所示
sealed interface Shape permits Rectangle, Square
record Rectangle() implements Shape
record Square() implements Shape
由于Rectangle
&;Square
是记录,因此它固有地使整个层次 struct 不可扩展,即不再允许更多的子类.
从JDK 21开始,switch
的模式匹配通过覆盖所有可能的case
或提供default
case 来覆盖其余部分,从而强制切换为穷举.
因此,对于低于switch
的案件,在什么情况下会执行default
起案件,因为所有可能的组合都包括在内,为什么甚至允许这样做?
switch (shape) {
case Rectangle r -> // do something with r;
case Square sq -> // do something with sq;
case null -> // shape could be null
default -> // WHY is this permitted when all possible cases are covered already??
}
P.S.:密封的层次 struct 当然可以进化,但当这种情况发生时,编译器会自动标记switch
来升级自己.