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

Enable empty lists inferred as double (eg: <double>[]) to return a zero of type double #73

Merged

Conversation

matthias-prevost
Copy link
Contributor

@matthias-prevost matthias-prevost commented Mar 14, 2024

I noticed that the CI is failing but doesn't seem to be caused by the modified code.

What was the problem ?

When using sumBy on an empty list with a type inferred as Iterable<double>, the method throws an error.
The error is :

type 'int' is not a subtype of type 'double' in type cast

Code in error :

N sumBy<N extends num>(N Function(T element) mapper) {
  ...
  return result as N; // located in: /lib/src/base/iterable_extension.dart:148
}

Step to reproduce :

<double>[].sumBy((e) => e)

Reason :
If the list is empty, the for loop will not be entered and the return will do return result as double; however result equals 0 and has type int at runtime.

Fix :
I propose to add an early return when the list is empty, we return either a zero from int or a zero from double depending on the type N is equal to. I had to create a small method that gets the expected zero since I did not find any better solution.

@matthias-prevost matthias-prevost marked this pull request as ready for review March 18, 2024 14:31
@marcglasberg marcglasberg merged commit d8f417d into marcglasberg:master Mar 22, 2024
1 check failed
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

Successfully merging this pull request may close these issues.

2 participants