Pattern matching on primitive types mxied with instanceof is a footgun

Askar Kalykov oxygene.core at gmail.com
Wed Feb 5 12:14:34 UTC 2025


Sorry for jumping in out of the blue,

to me, this is a problem of lack of visibility of exhaustiveness that
pattern matching brings. If before, we could just check for instanceof
AlienSpaceship and call it a covered path, now we treat `instanceof
AlienSpaceship` part as exhaustiveness check, and `AlienSpaceship(int x,
int y)` part as just mere unboxing.

Here, and from my other experience with pattern matching, I see the lack of
exhaustiveness plays a big part of misinterpreting the code. Simple
solution could really be opting for pushing the `var x, var y` notion in
all examples, while more permanent one is enforcing the exhaustiveness
somehow (maybe even requiring exhaustiveness everywhere where pattern
matching is used?)

On Tue, 4 Feb 2025 at 11:33, 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
>


-- 
(\_/)
(O.o)
(> <)
This is Bunny. Copy Bunny into your signature to help him on his way to
world domination.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-spec-observers/attachments/20250205/5661a51b/attachment.htm>


More information about the amber-spec-observers mailing list