mardi 14 février 2017

Clean way to pass a function as a parameter

Basically, I want to pass an arbitrary function (we don't know its signature) as a parameter for another "in a more natural way".

So let's presume I'm trying to write a timeit() function in Java that outputs the time it took for this arbitrary function to finish. Something like this:

Clock c = new Clock();

// Example 1
c.timeit(func1())

// Example 2
c.timeit(func2(a1, a2,...))

Right now, I'm doing something like this, but I don't like it. How can I re-write it to have the above form?

public class Clock implements Measure{    
    public void timeit(int i, IntConsumer m){
        //Save time1
        //call function m
        //Save time2
        //print time2-time1
    }
}

public static void main(String[] args){
    Clock c = new Clock();
    c.timeit(10, j-> func2(j));
}





Aucun commentaire:

Enregistrer un commentaire