More comprehensive type inference for pattern matching

Tagir Valeev amaembo at gmail.com
Thu Oct 10 10:24:17 UTC 2024


Hello!

This would basically bring flow-typing to Java (variable type may be
narrowed at use site, depending on the context; known as smart-casts in
Kotlin). I think, this is something Java tries to avoid. That's why a
instanceof B b introduces a new variable, rather than changes the type of a.

Another problem is that container.item instanceof Number does not imply
container instanceof Container<Number>. It could easily be
Container<Object>. Imagine

class Container<T> {
  T item, item2;
}

If you checked that item is Number, it doesn't mean that item2 is also
Number. It could be Container<Object> having Integer and String in the
fields. If you pass it to a place which accepts Container<Number> and reads
item2, you'll get a problem.

It's also possible that it's Container<Integer>, not Container<Number>.
Again, if you pass it to the place where Container<Number> is accepted, it
can rewrite your Integer field with Double, and later the code that still
assumes it's Container<Integer> will blow up.

With best regards,
Tagir Valeev


On Thu, Oct 10, 2024, 11:17 Nir Lisker <nlisker at gmail.com> wrote:

> Hi,
>
> Give a simple generic wrapper,
>
> class Container<T> {
>     T item;
> }
>
> pattern matching can find out what T is for 'item', but not for its
> container:
>
> void switchItem(Container<?> container) {
>     if (container.item instanceof Number num) {
>         acceptNumber(num);
>         acceptNumberContainer(container); // error
>     }
> }
>
> The information is technically there to make the derivation. I can
> envision some complexities with bound constraints, but seeing as I can't
> check 'instanceof Container<Number>`, can the compiler not be smarter?
>
> - Nir
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20241010/f4ec1678/attachment-0001.htm>


More information about the amber-dev mailing list