Dimitrios Desyllas
Dimitrios Desyllas

Reputation: 10048

How should I define a lambda in my method's arguments?

Ι have the following custom Runnable:

class RandomSum extends Runnable {

   public void run() {
     float sum - 0;
     for(int i = 0; i<1000000;i++){
       sum+=Math.random();
     } 
   }
}

And I want to run it like that:


  RandomSum s =new RandomSum();
  s.retrieveCallback((sum)->{
    System.out.println(sum);
  });
  Thread thread = new Thread();
  thread.start();

But I do not know how I should define the method retrieveCallback in RandomSum that accepts a lambda?

Upvotes: 1

Views: 56

Answers (2)

Pieter12345
Pieter12345

Reputation: 1789

You can define retrieveCallback within RandomSum as follows:

public void retrieveCallback(FeedbackHandler feedbackHandler) {
    int sum = ...; // Get the value however you like.
    feedbackHandler.handleFeedback(sum);
}

And then define this FeedbackHandler interface as:

public interface FeedbackHandler {
    void handleFeedback(int sum);
}

Essentially what happens when you pass lambda (sum) -> {...} to retrieveCallback is:

retrieveCallback(new FeedbackHandler() {
    @Override
    public void handleFeedback(int sum) {
        ...
    }
});

Upvotes: 1

Thiyagu
Thiyagu

Reputation: 17900

One possible target type of the lambda you've shown is a Consumer. Define a method setCallback accepting a Consumer<Float> and store it as an instance variable. Then invoke it after the for loop.

class RandomSum implements Runnable {
    Consumer<Float> callback;
   
    public void setCallback(Consumer<Float> callback) {
        this.callback = callback;
    }

    public void run() {
        float sum = 0;
        for(int i = 0; i<1000000;i++){
            sum += Math.random();
        } 
        callback.accept(sum);
    } 
}

Caller side

RandomSum s =new RandomSum();
s.setCallback((sum)->{
    System.out.println(sum);
});

Or using method references,

s.setCallback(System.out::println);

Preferably you can pass the callback in the constructor.

Upvotes: 1

Related Questions