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

Null-aware collection-for #3730

Open
anqit opened this issue Apr 27, 2024 · 3 comments
Open

Null-aware collection-for #3730

anqit opened this issue Apr 27, 2024 · 3 comments
Labels
feature Proposed language feature that solves one or more problems

Comments

@anqit
Copy link

anqit commented Apr 27, 2024

Currently, for collection-for's on nullable collections, we need a null check:

List<int>? myInts = ...;

if (myInts != null) {
    for (final i in myInts) {
        // use i
    }
}

It would be nice if we could have a null-aware version of this syntax, something along the lines of

for(final i in myInts?) ...

or

for(final i in? myInts) ...

which would skip iteration if the iterable were null.

Sorry if this already exists and I'm just (null-)unaware of it :)

@anqit anqit added the feature Proposed language feature that solves one or more problems label Apr 27, 2024
@lrhn
Copy link
Member

lrhn commented Apr 27, 2024

It does not exist. I'm not sure it will.

One issue is that you should rarely have a nullable collection, it's better to use an empty collection, and not have two ways to represent "no elements".
Another is that they syntax could be better used for something else.

If we get Null-aware elements (#323), then you should be able to write:

 for (final i in [?myInts]) { ... }

and with a little luck and prodding, the compiler should be able to optimize that into:

if (myInts case final myInts?) for (final i in myInts) { ... }

(if you don't want to write that out yourself).

@anqit
Copy link
Author

anqit commented Apr 27, 2024

you should rarely have a nullable collection

while largely I agree, one situation I have run into this is optional function parameters.
Also, do you mind explaining or linking to whatever pattern-matching foo is happening here:
if (myInts case final myInts?) ..., I don't think I've seen that syntax before

@julemand101
Copy link

@anqit https://dart.dev/language/pattern-types#null-check

It matches if myInts are not null and it will define a new variable called myInts inside the scope of the if-statement which have a non-nullable type.

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

3 participants