Pattern matching on primitive types mxied with instanceof is a footgun
Remi Forax
forax at univ-mlv.fr
Tue Feb 4 10:32:58 UTC 2025
Last week,
one of the TA for the course "OOP using Java" was grading student projects,
the subject of the project can be summarize to "you are alone in space and angry aliens want you to die".
One of the project had a weird bug when displaying aliens.
Spoiling the result of bug hunting, this is due to students using the pattern matching on primitive without them realizing it.
Here is a reproducer of the bug:
// in AlienSpaceship.java
record AlienSpaceship(double x, double y) implements Spaceship {
...
}
...
// in a method in another class
...
for(Spaceship spacehip : ...) {
...
if (spaceship instanceof AlienSpaceship(int x, int y) {
// display the alien space ship at (x, y)
}
...
}
The TA said she was about to give up when she found the issue and that the Java spec should not allow such pattern.
I agree with here, pattern matching on primitive types is not a feature people ask for and mixed with instanceof it's a footgun.
This feature can be re-introduced later using method patterns and it will be easier to understand the code,
by example with an hyphotethical method Double.asInt
if (spaceship instanceof AlienSpaceship(Double.asInt(int x), Double.asInt(int y)) {
...
regards,
Rémi
More information about the amber-spec-experts
mailing list