Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart: How to reduce a list of classes

Tags:

dart

I want to reduce a list of classes for example:

class Product {
  final String name;
  final double price;

  Product({this.name, this.price});
}

List<Product> products = [
  Product(name: 'prod1', price: 100.0),
  Product(name: 'prod2', price: 300.0),
];

void main() {
  var sum = products.reduce((curr, next) => curr.price + next.price);
  print(sum);
}

but it throws an error

Error: A value of type 'double' can't be assigned to a variable of type 'Product'.

like image 426
freeman29 Avatar asked Dec 17 '22 15:12

freeman29


1 Answers

The syntax for the reduce method are specified as:

reduce(E combine(E value, E element)) → E

So the method should return the same type as the two input. In you case the curr and next values are of the type Product but your are returning a double value.

What you properly want to use are instead the fold method:

fold<T>(T initialValue, T combine(T previousValue, E element)) → T

So you code would be:

class Product {
  final String name;
  final double price;

  Product({this.name, this.price});
}

List<Product> products = [
  Product(name: 'prod1', price: 100.0),
  Product(name: 'prod2', price: 300.0),
];

void main() {
  var sum = products.fold(0, (sum, next) => sum + next.price);
  print(sum);
}
like image 101
julemand101 Avatar answered Feb 02 '23 09:02

julemand101