001    package fp;
002    
003    /**
004     * Adding two Integers
005     * @author DXN
006     */
007    public class Add implements ILambda<Integer,Integer> {
008        public static final Add Singleton = new Add();
009        private Add() {
010        }
011        /**
012         * Adds zero to many Integer.
013         * @param params Integer[].
014         * @return Integer
015         */
016        public Integer apply(Integer ... params) {
017            // params is treated as Object[].
018            //  Integer[] p = (Integer[])params; // Not allowed in Java: Class Cast Exception!
019            int sum = 0;
020            // New Java 5.0 for loop:
021            for (Object i: params) {
022                sum += (Integer)i;  // auto-unboxing: ((Integer)i).intValue()
023            }
024    //        Traditional for loop (works OK):
025    //        for(int i = 0; i < params.length; i++) {
026    //            sum += (Integer)params[i];
027    //        }
028            return sum;  // auto-boxing: new Integer(sum)
029        }
030        
031        public static void main(String[] args){
032            ILambda<Integer,Integer> add = Add.Singleton;
033            System.out.println("Empty sum = " + add.apply());
034            System.out.println("1 = " + add.apply(1));
035            System.out.println("1 + 2 = " + add.apply(1, 2));
036            System.out.println("1 + 2 + 3 = " + add.apply(1, 2, 3));
037            System.out.println("1 + 2 + 3 + 4 = " + add.apply(1, 2, 3, 4));
038        }
039    }