Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Runnable and lambda

I could create a simple Runnable using lambda, like:

Runnable runnable = ()->{
    String message = "This is an hard coded string";
    System.out.println(message);
};

The limitation with above code it that it has created an Runnable with default constructor(with no arguments).

In practice, Runnable often take information when creating it,like the following:

class MyRunnable implements Runnable {
    private final String message;

    public MyRunnable(String message) {
        this.message = message;
    }

    @Override
    public void run() {
        System.out.println(message);
    }
 }

I would ask how to create lambda for Runnable that could take constructor arguments.

like image 967
Tom Avatar asked Oct 24 '17 07:10

Tom


1 Answers

There is no problem with having parameters from outside

private void runableWithParameter(final String message) {
    final Runnable runnable = ()->{
        System.out.println(message);
    };
}
like image 50
ByeBye Avatar answered Oct 11 '22 21:10

ByeBye