Skip to content

Instantly share code, notes, and snippets.

@matuella
Last active March 11, 2021 01:51
Show Gist options
  • Save matuella/68b430d41d66779e67be5430302afdf5 to your computer and use it in GitHub Desktop.
Save matuella/68b430d41d66779e67be5430302afdf5 to your computer and use it in GitHub Desktop.
Generic non nullable argument
void main() {
T nonNullableGeneric<T>(T value) {
if(value == null) {
throw 'This is null';
}
return value;
}
nonNullableGeneric(1); // Works fine
nonNullableGeneric(null); // Works fine BUT I would like that the type inference would not allow a nullable value
// Now this works as expected:
// "the argument type 'Null' can't be assigned to the parameter type 'int'."
//
// ... but I have to specify the type `T`, which is not clear given my function signature, that clearly
// requires a non-nullable value of type `T`
nonNullableGeneric<int>(null);
// How can I make the following call:
// nonNullableGeneric(null)
// to throw me something like "the argument type 'Null' can't be assigned to a parameter type 'T'."?
}
@matuella
Copy link
Author

matuella commented Mar 10, 2021

Solved by just extending the T argument with Object.

void main() {
  T nonNullableGeneric<T extends Object>(T value) {
    return value;
  }

  nonNullableGeneric(1); // Works fine
   
  // Throws a:
  // Couldn't infer type parameter 'T'. Tried to infer 'Null' for 'T' which doesn't work: Type parameter 'T' declared to extend 'Object'.
  // The type 'Null' was inferred from: Parameter 'value' declared as 'T' but argument is 'Null'.
  // Consider passing explicit type argument(s) to the generic
  nonNullableGeneric(null);
}

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