java compilation_error ai_generated true

错误:模式类型 'java.lang.String' 不是选择器表达式类型 'java.lang.Integer' 的子类型

error: pattern type 'java.lang.String' is not a subtype of the type of the selector expression 'java.lang.Integer'

ID: java/pattern-matching-invalid-type-test

其他格式: JSON · Markdown 中文 · English
95%修复率
85%置信度
1证据数
2024-01-08首次发现

版本兼容性

版本状态引入弃用备注
Java 17 active
Java 19 active
Java 21 active

根因分析

在 switch 表达式或模式匹配语句中,模式类型必须是选择器表达式类型的子类型;否则模式永远无法匹配,导致编译时错误。

English

In a switch expression or pattern matching statement, the pattern type must be a subtype of the selector expression's type; otherwise, the pattern can never match, leading to a compile-time error.

generic

官方文档

https://docs.oracle.com/en/java/javase/17/language/pattern-matching.html

解决方案

  1. 确保模式类型是选择器类型的子类型。例如,如果选择器是 `Number`,使用 `Integer i` 模式而不是 `String s`。修正后的代码:`switch (obj) { case Integer i -> ...; case String s -> ...; default -> ...; }`
  2. 使用密封接口或类来限制可能的类型,确保模式类型是子类型。
  3. 如果选择器类型是泛型类型,使用包含模式类型的通配符或类型参数,例如 `List<? extends Serializable>` 以允许 String 和 Integer 模式。

无效尝试

常见但无效的做法:

  1. Change the selector expression to match the pattern type by casting. 80% 失败

    Casting changes the compile-time type but may cause ClassCastException at runtime; the pattern should be written to handle the actual type hierarchy.

  2. Use `instanceof` in an if-else chain instead of switch. 50% 失败

    While this avoids the compile error, it doesn't leverage pattern matching's exhaustiveness and conciseness, and may reduce code readability.

  3. Add a default case with a cast pattern. 90% 失败

    The default case does not resolve the type mismatch; the pattern type must be a subtype of the selector type at compile time.