Search code examples
iterationdart

What is the cleanest way to get the sum of numbers in a collection/list in Dart?


I don't like using an indexed array for no reason other than I think it looks ugly. Is there a clean way to sum with an anonymous function? Is it possible to do it without using any outside variables?


Solution

  • Dart iterables now have a reduce function (https://code.google.com/p/dart/issues/detail?id=1649), so you can do a sum pithily without defining your own fold function:

    var sum = [1, 2, 3].reduce((a, b) => a + b);