Minor improvement to anonymous classes
Maurizio Cimadamore
maurizio.cimadamore at oracle.com
Thu Oct 7 14:36:55 UTC 2021
Your proposal is for anon classes, which I think works well.
One related case I found quite often is the desire to combine types e.g.
in a return type:
Foo & AutoCloseable getCloseableFoo();
This veers into declaration-land, visible to javadoc and all. So it
probably doesn't have a good benefit vs. cost ratio. Also, this is
effectively adding intersection types (I don't think restricting at
return types only will be feasible).
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.)
I'm not suggesting we have to solve this - just wanted to make sure this
was somewhere on the radar.
Maurizio
On 30/07/2021 15:52, Brian Goetz wrote:
> I have been working on a library where I've found myself repeatedly
> refactoring what should be anonymous classes into named (often local)
> classes, for the sole reason that I want to combine interfaces with an
> abstract base class:
>
> interface Foo { ... lots of stuff .. }
> abstract class AbstractFoo { ... lots of base implementation ... }
>
> interface RedFoo extends Foo { void red(); }
>
> and I want a factory that yields a RedFoo that is based on AbstractFoo
> and implements red(). Trivial with a named class, but there's no
> reason I should not be able to do that with an anonymous class, since
> I have no need of the name.
>
> We already address this problem elsewhere; there are several places in
> the grammar where you can append additional _interfaces_ with &, such as:
>
> class X<T extends Foo & Red> { ... }
>
> and casts (which can be target types for lambdas.)
>
> These are not full-blown intersection types, but accomodate for the
> fact that classes have one superclass and potentially multiple
> interfaces. It appears simple to extend this to inner class creation
> expressions:
>
> new AbstractFoo(args) & RedFoo { ... }
>
> This would also smooth out a rough edge refactoring between lambdas
> and anonymous classes.
>
> I suspect there are one or two other places in the spec that could use
> this treatment.
>
> (Note that this is explicitly *not* a call for "let's do full-blown
> intersection types"; this is solely about class declaration.)
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.java.net/pipermail/amber-spec-experts/attachments/20211007/0978af67/attachment.htm>
More information about the amber-spec-experts
mailing list