Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dart Fold method error – Summing a list int

New to Dart.

I’m getting error summing a List using the .fold() method:

List<int> listInt = [1, 2, 3, 4, 5, 6];
int sumList = listInt.fold(0, (p, c) => p + c);

// First Print  
print(sumList);

// Second Pring
print(listInt.fold(0, (p, c) => p + c));

Printing sumList is perfectly fine, but when I print the same operation i get a compilation error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The operator '+' can't be unconditionally invoked because the receiver can be 'null'.

Any ideas why?

Thanks in advance.

>Solution :

A case where the Dart type system is not smart enough to guess the correct type. What happens in your second line is that fold thinks you want a Object? returned so p becomes Object?.

In the first example, the Dart type system guesses the type based on the expected returned type which is int in your case. But because print expects Object?, you are really not getting the type you expect.

The reason is that the Dart type system does not really understand the concept of defining the returned type of a method given as second argument based on the type of the first argument. So fold is often problematic here if we don’t have an typed output.

We can force it to understand what we want by changing your second line to:

print(listInt.fold<int>(0, (p, c) => p + c));

And it should work as you want.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading