Type parameters inside super() calls?
Archie Cobbs
archie.cobbs at gmail.com
Thu Feb 2 16:10:06 UTC 2023
On Thu, Feb 2, 2023 at 9:20 AM Brian Goetz <brian.goetz at oracle.com> wrote:
> And when you extend to statements before the super, there's no reason they
> should not be in scope there.
>
Here's a plausible if a bit contrived example of needing a type parameter
prior to super():
import java.util.*;
import java.util.concurrent.atomic.*;
public class TypeParamCtorPrologue<T> extends AtomicReference<T> {
/**
* Initialize using the list element with the smallest hash code.
*/
public TypeParamCtorPrologue(List<T> objs) {
final T choice = objs.stream()
.sorted(Comparator.comparingInt(T::hashCode))
.findFirst();
.orElse(null);
super(choice);
}
}
The "choice" calculation could have also been inlined into the super()
call, so this is not a new problem with the spec.
Because of the reported compiler bug, that variant is (incorrectly) allowed
by the current compiler:
import java.util.*;
import java.util.concurrent.atomic.*;
public class TypeParamCtorPrologue<T> extends AtomicReference<T> {
/**
* Choose the object in the list with the smallest hash code.
*/
public TypeParamCtorPrologue(List<T> objs) {
super(objs.stream()
.sorted(Comparator.comparingInt(T::hashCode))
.findFirst()
.orElse(null));
}
}
So the current situation is one of two wrongs making a right.
I think the cure here is to simply update the constructor-body logic to say
> that this region is not a static context, but a restricted context in which
> you can't use this, super, instance members, etc. This is a small and
> localized change (to spec language we're already touching anyway.)
>
This would correct both wrongs at once and automatically fix the reported
bug. So I'm all for it :)
-Archie
--
Archie L. Cobbs
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/compiler-dev/attachments/20230202/e5178b8a/attachment.htm>
More information about the compiler-dev
mailing list