Skip to content

Implicit/explicit null safety in types and optional arguments #45256

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

Closed
larssn opened this issue Mar 9, 2021 · 2 comments
Closed

Implicit/explicit null safety in types and optional arguments #45256

larssn opened this issue Mar 9, 2021 · 2 comments

Comments

@larssn
Copy link

larssn commented Mar 9, 2021

So I'm on Dart 2.12, and I've run into a scenario where I have to feed null into a constructor, even though the parameter should be nullable.

class Test<T> {
  T _val;
  
  Test(this._val);
  
  @override
  String toString() {
    return _val == null ? 'T was nullable' : _val.toString();
  }
}

void main() {
  final nullable = Test<num?>(null);
  print(nullable);
  
  final nonnullable = Test(1);
  print(nonnullable);
}

The nullable variable needs null in order to get initialized which makes sense since the constructor takes a required argument.

What doesn't make sense though, is that even though I can inject my nullable types into the class, the constructor argument CANNOT be optional.

Wouldn't it make sense that the analyzer ignores types that originate from outside the class, since it cannot know whether they're nullable or not?

IMO only if the type extends some kind of actual type, can the Test class start making assumptions towards nullability.

@lrhn
Copy link
Member

lrhn commented Mar 9, 2021

A parameter is either always optional or always required. That does not depend on the its type.
If the parameter is required, then you need to pass a valid value, whether the parameter is nullable or not. If it is nullable, then null is a valid value, but no more special than any other valid value.
You are not forced to pass null to Test<num?>(null), you could also use Test<num?>(0)

If the parameter is optional, it's either nullable or it has a default value. When the type of the parameter is a type variable, then it's not possible to have a default value (there is no value which is valid for all types that can be the type argument), so the parameter must either be made definitely nullable (typed as T?) or it must be required.

We did think about whether we could combine nullability and optionality in parameters, but did not find a good model that everybody could agree on.

See also #39897, #33918.

@larssn
Copy link
Author

larssn commented Mar 9, 2021

Yeah I can imagine it being tricky combining the two.

Thanks for clarifying.

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

No branches or pull requests

2 participants