sealed class 修饰符如何帮助 Java 中的模式匹配?

How sealed class modifier helps with pattern matching in Java?

最新的 Java 版本 15 提供了新功能 - sealed 修饰符。我浏览了 JEP,上面写着:

Sealed classes and interfaces restrict which other classes or interfaces may extend or implement them.

Goals:

  • Allow the author of a class or interface to control which code is responsible for implementing it.
  • Provide a more declarative way than access modifiers to restrict the use of a superclass.
  • Support future directions in pattern matching by underpinning the exhaustive analysis of patterns.

第一个和第二个很简单,但是第三个很难理解。请有人解释一下,sealed 将如何帮助 pattern matching

making a class sealed 意味着编译器在编译时知道完整的实现列表classes。因此,它可以确认(例如)每个可能的匹配项都已处理。

将其视为类似于已检查的异常:在编译时,编译器确保以某种方式处理可能抛出的每个已检查的异常(通过捕获或通过 throws 子句),因此可以保证流量控制将在形式上保持一致。