Skip to content

?? operator does not allow 'return' or 'throw' #2095

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
imrhk opened this issue Feb 5, 2022 · 4 comments
Closed

?? operator does not allow 'return' or 'throw' #2095

imrhk opened this issue Feb 5, 2022 · 4 comments
Labels
feature Proposed language feature that solves one or more problems

Comments

@imrhk
Copy link

imrhk commented Feb 5, 2022

In Kotlin, I have been used to arg ?: return to check if function argument is null or some other variable is null. If that's the case, return immediately. In android this was really helpful where I did context ?: return in Android apps.

I tried doing the same with ?? operator but I wasn't successful.
Like for ScrollController? _scrollController data member, I want to do
final scrollController = _scrollController ?? return

This basically means if variable is null, return or set the value as final where object is non-null.

As far as the feature goes, it works for throws as well. Ref: https://kotlinlang.org/docs/null-safety.html#elvis-operator

@imrhk imrhk added the feature Proposed language feature that solves one or more problems label Feb 5, 2022
@Semvrij
Copy link

Semvrij commented Feb 5, 2022

Can you take a look at #2088 and #2025 ? This is probably a duplicate.

@lrhn
Copy link
Member

lrhn commented Feb 5, 2022

Also, Dart does allow using throw as an expression, you just need parentheses for precedence reasons:

final scollController= _scrollController ?? (throw StateError("No scroll controller?!?"));

@eernstg
Copy link
Member

eernstg commented Feb 9, 2022

@imrhk, I think the discussion in #2025 covers this issue to a very high degree. So perhaps it would be useful to close this issue, and take the discussion in #2025 instead?

@leafpetersen
Copy link
Member

Closing in favor of #2025 .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature Proposed language feature that solves one or more problems
Projects
None yet
Development

No branches or pull requests

6 participants