Lambda for JavaFX Task [英] Lambda for JavaFX Task

查看:136
本文介绍了Lambda for JavaFX Task的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编译器为此代码提供了此错误lambda表达式的目标类型必须是一个接口:

The compiler gives me this error "Target Type of lambda expression must be an interface" for this code:

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

listFiltered()的返回类型是可迭代<显示>
如何在lambda中使用任务界面?

listFiltered()'s return type is Iterable<Showing>. How can I use the Task interface with lambda?

推荐答案

任务是一个抽象类,而不是一个接口,因此无法使用lambda表达式直接创建它。

Task is an abstract class, not an interface, and so it cannot be directly created with a lambda expression.

您通常只使用内部类来子类任务

You would typically just use an inner class to subclass Task:

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

如果您想要创建任务使用lambda表达式,您可以创建一个可重用的实用程序方法来为您执行此操作。由于您需要在 Task 中实现的抽象方法 call 与<$ c中的接口方法具有相同的签名$ c> Callable ,您可以执行以下操作:

If you want the functionality of creating a Task with a lambda expression, you could create a reusable utility method to do that for you. Since the abstract method call that you need to implement in Task has the same signature as the interface method in Callable, you could do the following:

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();
            }
        };
    }
}

由于可调用是一个 FunctionalInterface (即一个带有单个抽象方法的接口),它可以用lambda表达式创建,所以你可以做到

Since Callable is a FunctionalInterface (i.e. an interface with a single abstract method), it can be created with a lambda expression, so you could do

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

有一个解释为什么不允许使用lambda来创建(有效)抽象类的子类,并使用单个抽象方法OpenJDK邮件列表。

There is an explanation of why lambdas are not allowed to be used to create (effectively) subclasses of abstract classes with a single abstract method on the OpenJDK mailing list.

这篇关于Lambda for JavaFX Task的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆