About fold function in Chapter 2 anonymous function

const evens = [2, 4, 6, 8, 10, 12];
final total = evens.fold<int>(
  (sum, element) => sum + element,

Hi I don’t quite understand why I need to add <int> after fold? What is the implication of it?

However, I copy some example codes from another website, like below:

List<String> names = ["John", "Doe", "Jane", "Doe"];
int totalNamesLength = names.fold(0, (totalLength, element) => totalLength + element.length);
print(totalNamesLength); // 14

The code doesn’t need <int>

1 Like

Good point. I don’t even remember now why I added it. It might have been that the Dart analyzer was warning me to add it at the time I wrote the example. But even if that was true then, it’s not giving a warning without it anymore.

The short answer is both ways are ok.

Argument for adding the type:

  • fold is a generic function and it’s a generally a good rule to explicitly specify the type with generics. (See chapter 8, “Generics” for more about generic types.) For example, Writing List<String> is more explicit than writing List. Writing the type yourself helps Dart to know what it is when there is any ambiguity.

Arguments against adding the type:

  • Dart can already figure out the type here just from the context (that is, by using type inference), so there is no need on Dart’s part for you to tell it.
  • At this point in the book, we haven’t studied generics, so the less we use them, the less confusion there will be for readers.

The arguments against sound stronger to me, so I’m removing the <int> from fold<int> both here and in the challenge solution. Thank you for your question.


@suragch thank you, very clear explanation. I also would like to add the point as I use the latest SDK 2.19.0, Dart can infer the type and there is no error.
For older SDK, it may said sum + element may have null value because total’s type is dynamic. If you don’t want to introduce generics, you can specify the type for total. See the code below:

  final int total = evens.fold(
    (sum, element) => sum + element,

above code has no error even for lower SDK.


Hi @ellery,

Thank you for your constant engagement on our community. We hope that the response provided by @suragch was helpful in addressing your concerns.

If you have any further questions or need additional assistance, please don’t hesitate to ask.