0

I know TypeScript ain't Java but I thought this could work. Unfortunately I figure out that probably this inside mainFunction is referring to the mainFunction it self, since functions are first-class citizens, right?

class MathClass<T> {
    total: T;
    increment:number = 0;

    constructor(value:T) {
        this.total = value;
    }

    mathFunction(num:T) {
        this.increment++;
        console.log(this.increment + ")" + this.total );
    }
}

var list:Array<number> = [1,2,3,4,5,6];
var mathClass = new MathClass<number>(0);
list.forEach(mathClass.mathFunction);

output:

NaN)undefined
NaN)undefined
NaN)undefined
NaN)undefined
NaN)undefined
NaN)undefined

While in Java 8 I could do this

public class StaticMethodClass<T> implements Consumer<T> {
    private T total;
    private int increment= 0;
    private BiFunction biFunction;

    StaticMethodClass(T value,BiFunction<T,T,T> biFunction) {
        this.total = value;
        this.biFunction = biFunction;
    }

    public void accept(T t) {
        this.increment++;
        this.total = (T) this.biFunction.apply( this.total, t );
        System.out.println(this.increment + ")" + this.total );
    }

    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1,2,3,4,5,6 );
        list.forEach( new StaticMethodClass<Integer>(6,(a,b) -> a + b) );
    }
}

Output

1)1
2)3
3)6
4)10
5)15
6)21

So is it possible to implement the same in Typescript?

giannis christofakis
  • 8,201
  • 4
  • 54
  • 65

0 Answers0