Minor improvement to anonymous classes

Alan Malloy amalloy at google.com
Thu Oct 7 21:25:54 UTC 2021


You can't actually do this: that signature is a promise to return an
instance of *any* class implementing those interfaces, not *some* class
implementing them. If you try to implement your getCloseableFoo method,
you'll find that no implementation compiles. For example:

final class tmp {
  static <X extends AutoCloseable & Serializable> X getX() {
    class Impl implements AutoCloseable, Serializable {
      public void close() {}
    }
    return new Impl();
  }
}

tmp.java:8: error: incompatible types: Impl cannot be converted to X
    return new Impl();
           ^
  where X is a type-variable:
    X extends AutoCloseable,Serializable declared in method <X>getX()

This is because some caller may define their own MyImpl class implementing
those interfaces, and then write MyImpl i = getX(), instantiating X to
MyImpl, and your method doesn't know how to build such an object.

On Thu, Oct 7, 2021 at 7:37 AM Maurizio Cimadamore <
maurizio.cimadamore at oracle.com> wrote:

> But I'm puzzled by the fact that programmers can, in a way, do something
> similar to the above with a generic method:
>
> <X extends Foo & AutoCloseable> X getCloseableFoo();
>
> Which kind of works, but it's quite an horrible hack (you introduce a type
> parameter you don't need - which means compiler will try to infer types,
> etc.)
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.java.net/pipermail/amber-spec-experts/attachments/20211007/86059a43/attachment.htm>


More information about the amber-spec-experts mailing list