Type pattern and raw type

Remi Forax forax at univ-mlv.fr
Mon Mar 15 11:08:11 UTC 2021


Hi, currently when there is an instanceof + type pattern with a raw type,
javec doesn't raise any warning (oops), worst it compiles because i believe it should not, but for that, the spec has to be amended.

  interface Foo<T> {
    void set(T t);
  }

  class FooImpl implements Foo<String> {
    private String value;

    @Override
    public void set(String s) {
      value = s;
    }
  }

  public static void main(String[] args) {
    Object o = new FooImpl();
    if (o instanceof Foo foo) {
      foo.set(3);
    }
  }

The JLS 14.30.2 says
"An expression, e, that is not the null literal is compatible with a type test pattern of type T if e can be converted to type T by a casting conversion (5.5), and the casting conversion does not make use of a narrowing reference conversion which is unchecked (5.1.6.2)."

Unchecked conversions are forbidden because of type pollution, that why you can not write
  if (o instanceof Foo<Integer> foo) {

Raw type conversions also leads to type pollution, so i think that a type pattern with a raw type should be forbidden too.

So at least, javac should raise a warning and IMO the spec should be amended to fordid raw types too.

regards,
Rémi


More information about the amber-spec-experts mailing list