Pattern matching on primitive types mxied with instanceof is a footgun
Brian Goetz
brian.goetz at oracle.com
Tue Feb 4 11:44:53 UTC 2025
Wow, that was pretty amazing. You went from “one student, who was never taught about how this works, was confused by it” to “ let’s pull the whole feature “ in one breath.
> On Feb 4, 2025, at 11:33 AM, Remi Forax <forax at univ-mlv.fr> wrote:
>
> 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