Lambda for JavaFX Task

The compiler provided this error for this Code: "the target type of a lambda expression must be an interface":

Task<Iterable<Showing>> task = () -> sDAO.listFiltered();

The return type of listfiltered() is iterative < showing > How to use the task interface in lambda?

Solution

Task is an abstract class, not an interface, so it cannot be created directly using lambda expressions

You typically subclass tasks using only internal classes:

Task<Iterable<Showing>> task = new Task<Iterable<Showing>>() {
    @Override
    public Iterable<Showing> call throws Exception {
        return sDAO.listFiltered();
    }
});

If you want to use lambda expressions to create tasks, you can create a reusable utility method to do this for you Since the abstract method call you need to implement in task has the same signature as the interface method in callable, you can perform the following operations:

public class Tasks {

    public static <T> Task<T> create(Callable<T> callable) {
        return new Task<T>() {
            @Override
            public T call() throws Exception {
                return callable.call();
            }
        };
    }
}

Since callable is a functional interface (that is, an interface with a single abstract method), it can be created using lambda expressions, so you can do this

Task<Iterable<Showing>> task = Tasks.create(() -> sDAO.listFiltered());

There is an explanation why Lambdas is not allowed to create subclasses of (valid) abstract classes using a single abstract method on the openjdk mailing list

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>