The `fold` method in Dart reduces a collection to a single value by iteratively combining each element of the collection with an existing value.
The syntax of Runes.fold() method is:
T fold<T>(T initialValue, T combine(T previousValue, int element))
This fold() method of Runes reduces a collection to a single value by iteratively combining each element of the collection with an existing value.
Parameter | Optional/Required | Description |
---|---|---|
initialValue | required | The initial value to start the accumulation. |
combine | required | A function that takes the previous accumulated value and the current element, and returns the new accumulated value. |
Runes.fold() returns value of type T
.
In this example,
numbers
containing integers.fold()
method with an initial value of 0 and a function that adds the previous value to the current element.void main() {
List<int> numbers = [1, 2, 3];
int sum = numbers.fold(0, (previousValue, element) => previousValue + element);
print(sum);
}
6
In this example,
words
containing strings.fold()
method with an initial value of an empty string and a function that concatenates each word with a space.void main() {
List<String> words = ['hello', 'world'];
String combined = words.fold('', (previousValue, word) => previousValue + word + ' ');
print(combined.trim());
}
hello world
In this example,
uniqueNumbers
containing integers.fold()
method with an initial value of 1 and a function that multiplies the previous value with the current number.void main() {
Set<int> uniqueNumbers = {1, 2, 3};
int product = uniqueNumbers.fold(1, (previousValue, number) => previousValue * number);
print(product);
}
6
In this Dart tutorial, we learned about fold() method of Runes: the syntax and few working examples with output and detailed explanation for each example.