Reducing verbosity for generics

Archie Cobbs archie.cobbs at gmail.com
Mon Jun 10 22:53:40 UTC 2024


On Mon, Jun 10, 2024 at 4:05 PM Johannes Spangenberg <
johannes.spangenberg at hotmail.de> wrote:

> and any implementation of withFoo() would just have to return an object
> with type compatible with Builder<T>.
>
> With these rules, the compiler would allow the following code, although it
> is broken:
>
> public class Builder { // May have sub-types
>     ...
>     this.class copy() {
>         return new Builder(this);
>     }
>     ...
> }
>
> Oops, you're right I didn't think of that. But there's an easy fix :)

public class Builder<T> {

    private final Function<this.class, this.class> copyConstructor;

    protected Builder(Function<this.class, this.class> copyConstructor) {
        this.copyConstructor = copyConstructor;
    }

    public this.class copy() {
        return this.copyConstructor.apply(this);
    }
}

> Anyway, there are probably solutions to make it work in most situations
> using more elaborate rules for the type system. I guess you could also
> argue that it is OK that the compiler cannot detect the broken code above,
> and the application should just throw a ClassCastException. After all, it
> wouldn't be the only case where broken code is not detect at compile time.
> However, I think such change would require careful consideration of
> different solutions to the problem (and whether the problem justifies
> special syntax and rules).
>
Agree.. there could be proper checks but it starts to get a little ugly.
The compiler would disallow classes that override a supertype containing
such methods without overriding each of them. For completeness you'd also
want to detect violations at the JVM level as well and throw
IncompatibleClassChangeError, etc.

-Archie

-- 
Archie L. Cobbs
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20240610/4ce1bd2d/attachment.htm>


More information about the amber-dev mailing list