JDK17+:为什么不可能在多个类型模式上进行单个 switch 分支匹配?
只是想知道这是/是什么设计的理由。
我可以做,
int x = ...
switch( x ) {
case 1,2 -> { ... stuff ...}
default -> { ... something else ...}
}
但是尝试做类似
Object x = ...
switch( x ) {
case String, Integer x -> { ... stuff ...}
default -> { ... something else ...}
}
不编译的事情(我还尝试了诸如“字符串x,integer x”和“ string | integer x”之类的东西,但它们都没有编译)。
如果我理解 jls 正确地,它根本不支持 - 有人知道为什么是这种情况吗?
Just wondering what the design rationale for this is/was.
I can do
int x = ...
switch( x ) {
case 1,2 -> { ... stuff ...}
default -> { ... something else ...}
}
but trying to do something like
Object x = ...
switch( x ) {
case String, Integer x -> { ... stuff ...}
default -> { ... something else ...}
}
does not compile (I also tried things like "String x, Integer x" and "String|Integer x" but neither of them compile).
If I understood the JLS correctly, it's simply not supported - does anybody know why this is the case and if this will ever be fixed ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
再次阅读JEP-420后,我发现了一个解释:
我仍然认为,如果分支机构实际上没有指案例标签,例如在这样的代码中,这是可能的(ApplicationState是一个密封类带有几个子类,请注意,我在这里无法使用枚举,因为一些州需要持有可变数据):
After reading JEP-420 again I found an explanation:
I still think this should be possible if the body of the branch does not actually refer to the case labels, for example in code like this (ApplicationState is a sealed class with several subclasses, note that I cannot use an enum here as some of the states need to hold mutable data):