package de.bwaldvogel.mongo.backend.aggregation;

class SumAccumulator extends Accumulator {

    private Number sum;

    SumAccumulator(Object expression) {
        super(expression);
    }

    @Override
    public void aggregate(Object value) {
        if (value instanceof Number) {
            Number numberValue = (Number) value;
            if (sum == null) {
                sum = numberValue;
            } else {
                if (sum instanceof Double || value instanceof Double) {
                    sum = sum.doubleValue() + ((Number) value).doubleValue();
                } else if (sum instanceof Integer && value instanceof Integer) {
                    sum = sum.intValue() + ((Integer) value).intValue();
                } else if (value instanceof Long) {
                    sum = sum.longValue() + ((Long) value).longValue();
                } else {
                    throw new UnsupportedOperationException();
                }
            }
        }
    }

    @Override
    public Object getResult() {
        if (sum != null) {
            return sum;
        } else {
            return 0;
        }
    }
}

@@ -43,16 +43,59 @@
 ation;%0A%0A
+import de.bwaldvogel.mongo.backend.Utils;%0A%0A
 class Su
@@ -152,16 +152,20 @@
 mber sum
+ = 0
 ;%0A%0A    S
@@ -344,842 +344,135 @@
     
-Number numberValue = (Number) value;%0A            if (sum == null) %7B%0A                sum = numberValue;%0A            %7D else %7B%0A                if (sum instanceof Double %7C%7C value instanceof Double) %7B%0A                    sum = sum.doubleValue() + ((Number) value).doubleValue();%0A                %7D else if (sum instanceof Integer && value instanceof Integer) %7B%0A                    sum = sum.intValue() + ((Integer) value).intValue();%0A                %7D else if (value instanceof Long) %7B%0A                    sum = sum.longValue() + ((Long) value).longValue();%0A                %7D else %7B%0A                    throw new UnsupportedOperationException();%0A                %7D%0A            %7D%0A        %7D%0A    %7D%0A%0A    @Override%0A    public Object getResult() %7B%0A        if (sum != null) %7B%0A            return sum;%0A        %7D else %7B%0A            return 0;%0A        %7D
+sum = Utils.addNumbers(sum, (Number) value);%0A        %7D%0A    %7D%0A%0A    @Override%0A    public Object getResult() %7B%0A        return sum;
 %0A   

Simplify SumAccumulator #28