Skip to content

Do we need a generic constraint for nullable only generics? #143

@leafpetersen

Description

@leafpetersen

The following class will be ill-formed when we move to non-nullable types:

class C<T> {
  T x;  // Error, since T may be non-nullable, and x is not initialized
  List<T> l = new List(10); // Error, since T may be non-nullable and the list is not initialized
}

One solution is to simply require the user to manually put a ? on the type where required:

class C<T> {
  T? x;  
  List<T?> l = new List(10);
}

Another possibility is to allow the class to specify a constraint indicating that it may only be applied to nullable types:

class C<T?> {  // T is required to be nullable
  T x;   // Ok, required to be nullable
  List<T> l = new List(10); // Ok, required to be nullable
}

It's not clear how common this is. Also, this is something that could probably be added later if we discover we really want it (though changing classes to use it would be a breaking library change).

cc @lrhn @munificent @eernstg

Metadata

Metadata

Assignees

Labels

nnbdNNBD related issues

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions