如何传递和使用任意lambda函数作为参数

use*_*434 6 java lambda java-8

我对Lisp中的lambda函数有很好的理解.Java似乎没有Lisp那样的灵活性.我如何在Java中考虑lambdas?鉴于下面的代码,我该怎么做?

public class Draw {
    GraphicsContext gc;

    static void draw(double x, double y, double w, double h, boolean drawRect) {
        if (drawRect) {
            gc.fillRect(x, y, w, h);
        } else {
            gc.strokeRect(x, y, w, h);
        }
    }

    // How do I do that?
    static void drawWithLambda(double x, double y, double w, double h /**, lambda */) {
        lambda(x, y, w, h);
    }

    public static void main(String[] args) {
        draw(0, 0, 50, 50, false); // OK
        drawWithLambda(0, 0, 50, 50, GraphicsContext::fillRect); // Ok?
    }
}
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 3

您必须指定方法参数实现的功能接口的类型lambda

drawWithLambda(double x, double y, double w, double h, SomeFuncInterface lambda) {
    lambda.someMethod (x, y, w, h); // someMethod is the single method that
                                    // SomeFuncInterface implements
}
Run Code Online (Sandbox Code Playgroud)

为了让这条线工作

drawWithLambda(0, 0, 50, 50, GraphicsContext::fillRect);
Run Code Online (Sandbox Code Playgroud)

fillRect的方法GraphicsContext必须与功能接口的方法的签名兼容SomeFuncInterface

BTW,GraphicsContext::fillRect是方法引用,而不是 lambda 表达式。您可以传递 lambda 表达式、方法引用或函数接口的任何其他实现(常规类实例、匿名类实例等)。