1

I would like to simplify a piece of code (see below) to a lambda expression:

Task<Void> sleeper = new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                }
                return null;
            }
        };

I tried to simplify it like this:

1/

Task<Void> sleeper = () ->{ Thread.sleep( 5000 ); };

2/

Worker<Void> sleeper = () ->{ Thread.sleep( 5000 ); };

Unfortunately both solution do not compile as task is not an interface and Worker has multiple non-overriding methods

is it possible to simplify it ?

thanks

bioinfornatics
  • 1,749
  • 3
  • 17
  • 36
  • Possible duplicate of [JAVA FX - Lambda for Task interface](http://stackoverflow.com/questions/30089593/java-fx-lambda-for-task-interface) – MikaelF Jan 30 '17 at 19:54

1 Answers1

1

Short answer: no, you can't simplify it.

Why? As you already pointed out, you can't because to use lambdas here you need a functional interface, and an abstract class like Task can't be a functional interface, even though it has only one abstract method. In the Worker class you have multiple abstract methods, so also in that case a lambda can't work, as you need to implement all of the abstract methods in order to instantiate this class.

user7291698
  • 1,972
  • 2
  • 15
  • 30