简体   繁体   中英

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?

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.

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) {
        ...
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM