How to call function with callbacks in Java like I do it in C#?

android, c#, delegates, java

Solution

Since closures are not supported yet you have to use interface and anonymous inner class.

private void ParentFunc {
    WorkerClass worker = new WorkerClass();

    worker.doWork(new Callback<Integer>() {
        public void invoke(Integer arg) {
            System.out.println("Progress" + arg);
        }
    });
}

public class WorkerClass {
    public doWork(Callback<Integer> callback) {
        for (int i=1; i<1000; i++) callback.invoke(i);  
    }
}

public interface Callback<T> {
    public void invoke(T arg);
}

Problem

I'm pretty new to Java but I need to write something like this C# code (this is hand-typed prototype just to illustrate what I need) ``` private void ParentFunc() { var worker = new WorkerClass() worker.DoWork(e => console.Write("Progress" + e)); } public class WorkerClass() { public method DoWork(Action<int> callback) { for (int i=1; i<1000; i++) callback.Invoke(i); } } ``` Little explanation. I'm using `AsyncTask` in android and calling outside processor classed but would like them to signal back so I can `publishProgress`. I prefer not to put interface over my `AsyncTask`

Original source

Related problems