0

I am new to Java and trying to pass a function as an argument that gets called when a certain event occurs. I came across Callable and found a few answers for similar problems but not this exactly.

Currently, my code is doing this

doSomething(new Callable<Void>() {
  public Void call() {
    System.out.println("callback called! ");
    return null;
  }
});

But I want this :

doSomething(new Callable<Void>() {
  public Void call(String foo) { // Want this function to accept parameters
    System.out.println("callback called with string " + foo);
    return null;
  }
});
molecule
  • 1,027
  • 1
  • 14
  • 27

1 Answers1

0

The java.util.function.Consumer functional interface is exactly what you are looking for: accepts a single argument and returns no output.

You need to do something like:

    doSomething(new Consumer<String>() {
        @Override
        public void accept(String foo) {
            System.out.println("Consumer called with string " + foo);
        }
    });

Or even better, replace it with a lambda:

doSomething(foo -> System.out.println("Consumer called with string " + foo));

doSomething looks like this:

void doSomething(Consumer<String> stringConsumer) {
    stringConsumer.accept("Hello!");
}
lkatiforis
  • 5,703
  • 2
  • 16
  • 35