Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Restrict the instantiation type on a constructor #1330

Open
mernst opened this issue Jun 8, 2017 · 1 comment
Open

Restrict the instantiation type on a constructor #1330

mernst opened this issue Jun 8, 2017 · 1 comment

Comments

@mernst
Copy link
Member

mernst commented Jun 8, 2017

It is desirable to specify the result type (the "return type") of a constructor.

For example, new TreeSet<Integer>() has type TreeSet<@NonNull Integer>, but other treesets can permit nullable elements.

More generally, we wish to permit the first two constructor calls but forbid the last two.

   new TreeSet<@Nullable Integer>(new IntegerOrNullComparator()); 
   new TreeSet<Integer>(); 

   //:: error: (type.argument.type.incompatible) 
   new TreeSet<@Nullable Integer>(); 
   //:: error: (type.argument.type.incompatible) 
   new TreeSet<@Nullable Integer>(new IntegerComparator()); 

Java provides syntax for restricting the receiver type on an instance method, but no syntax for type parameter annotations on the constructor result. Only a type annotation, not a full type which would include type parameters, can precede a constructor declaration. So, we would need to make up a new annotation to express the constraint.

There are likely to be classes other than TreeSet that need to utilize this new mechanism.

@graememorgan
Copy link

Another example of that is AtomicReference. It's desirable for the type arg to express the nullability of the reference, but the argumentless constructor initialises the reference to null.

AtomicReference<Integer> ref = new AtomicReference<>();
ref.get().hashCode(); // surprise NPE.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants