# 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`
- **Domain:** java
- **Category:** compilation_error
- **Verification:** ai_generated
- **Fix Rate:** 95%

## 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.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| Java 17 | active | — | — |
| Java 19 | active | — | — |
| Java 21 | active | — | — |

## Workarounds

1. **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 -> ...; }`** (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 -> ...; }`
   ```
2. **Use a sealed interface or class to restrict the possible types and ensure the pattern types are subtypes.** (90% success)
   ```
   Use a sealed interface or class to restrict the possible types and ensure the pattern types are subtypes.
   ```
3. **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.** (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.
   ```

## Dead Ends

- **Change the selector expression to match the pattern type by casting.** — Casting changes the compile-time type but may cause ClassCastException at runtime; the pattern should be written to handle the actual type hierarchy. (80% fail)
- **Use `instanceof` in an if-else chain instead of switch.** — While this avoids the compile error, it doesn't leverage pattern matching's exhaustiveness and conciseness, and may reduce code readability. (50% fail)
- **Add a default case with a cast pattern.** — The default case does not resolve the type mismatch; the pattern type must be a subtype of the selector type at compile time. (90% fail)
