PROPOSAL: fold keyword

Joshua Bloch jjb at
Thu Mar 5 13:28:11 PST 2009


This doesn't seem compelling.

Here's your simple example:

    // sum all numbers in the list
    Integer sum =
    fold(Integer n : list;     // iterating collection element n
         Integer result = 0) { // Where to accumulate the result, and
             the initial value
             result += n;

And here's how it looks today (with no change to the language or libraries):

    Integer sum = 0;
    for (Integer n : list)
        sum += n;

Here's one of your complex examples:

  // returns a new collection with the salaries of the employees not on
 List<BigDecimal> salaries =
   fold(Employee e : emps;
        List<BigDecimal> newList = new ArrayList<BigDecimal>()) {
     if (!e.onVacation()) {

And here's how it looks today:

     List<BigDecimal> salaries = new ArrayList<BigDecimal>();
     for (Employee e : emps)
         if (!e.onVacation())

To my eyes, the current version is clearer as well as shorter.


More information about the coin-dev mailing list