java compilation_error ai_generated true

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

Also available as: JSON · Markdown · 中文
95%Fix Rate
85%Confidence
1Evidence
2024-01-08First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
Java 17 active
Java 19 active
Java 21 active

Root Cause

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

中文

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

Official Documentation

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

Workarounds

  1. 95% success Ensure the pattern type is a subtype of the selector type. For example, if selector is `Number`, use `Integer i` pattern instead of `String s`. Corrected code: `switch (obj) { case Integer i -> ...; case String s -> ...; default -> ...; }`
    Ensure the pattern type is a subtype of the selector type. For example, if selector is `Number`, use `Integer i` pattern instead of `String s`. Corrected code: `switch (obj) { case Integer i -> ...; case String s -> ...; default -> ...; }`
  2. 90% success Use a sealed interface or class to restrict the possible types and ensure the pattern types are subtypes.
    Use a sealed interface or class to restrict the possible types and ensure the pattern types are subtypes.
  3. 85% success If the selector type is a generic type, use a wildcard or type parameter that includes the pattern type, e.g., `List<? extends Serializable>` to allow both String and Integer patterns.
    If the selector type is a generic type, use a wildcard or type parameter that includes the pattern type, e.g., `List<? extends Serializable>` to allow both String and Integer patterns.

中文步骤

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

Dead Ends

Common approaches that don't work:

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

    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% fail

    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% fail

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