Mileage and lambda

I could create a simple Runnable using lambda, for example:

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

The limitation with the code above means that he created Runnable with a standard constructor (no arguments).

In practice, Runnable often accepts information when it is created, for example:

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 a lambda for Runnable that can take constructor arguments.

+6
source share
1 answer

No problem with parameters outside

private void runableWithParameter(final String message) {
    final Runnable runnable = ()->{
        System.out.println(message);
    };
}
+4
source

All Articles