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

Add shorthand for null-aware method execution #44698

Closed
enloc-port opened this issue Jan 18, 2021 · 3 comments
Closed

Add shorthand for null-aware method execution #44698

enloc-port opened this issue Jan 18, 2021 · 3 comments
Labels
closed-as-intended Closed as the reported issue is expected behavior

Comments

@enloc-port
Copy link

enloc-port commented Jan 18, 2021

Say a class had a nullable method, i.e. an optional callback.

class Foo {
  Foo([this.doSomething]);
  final int Function() doSomething;
}

In order to avoid an error, I have to do a null-check on the method before executing it:

void main() {
  Foo foo = Foo();
  if (foo.doSomething != null) {
    foo.doSomething();
  }
}

But it would make the code look a lot cleaner, if this were possible:

void main() {
  Foo().doSomething?(); // null-aware execution
}
@eernstg
Copy link
Member

eernstg commented Jan 18, 2021

The syntax for that feature is as follows:

class Foo {
  Foo([this.doSomething]);
  final int Function()? doSomething;
}

void main() {
  Foo().doSomething?.call(); // null-aware execution
}

We did discuss allowing f?(args) as a way to invoke f on arguments args if f is non-null and otherwise skip. But f?.call(args) does exactly that already, so the need isn't that urgent, and it may create some grammar ambiguities so it wasn't considered worthwhile.

@enloc-port
Copy link
Author

I see. Well, f?(args) would be sweet, but I guess I could live with f?.call(args).

@enloc-port enloc-port changed the title Make null-aware method execution possible Add shorthand for null-aware method execution Jan 18, 2021
@eernstg eernstg added the closed-as-intended Closed as the reported issue is expected behavior label Jan 18, 2021
@eernstg
Copy link
Member

eernstg commented Jan 18, 2021

Thanks! I think we should close this issue because the code is working as intended. Please create a new issue as needed, for instance, if you wish to make it a language proposal (in the language repository). Most likely, it could be a comment on dart-lang/language#404.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
closed-as-intended Closed as the reported issue is expected behavior
Projects
None yet
Development

No branches or pull requests

2 participants