简体   繁体   English

为什么无法从枚举构造函数的 lambda 访问实例成员?

[英]Why can't the instance member be accessed from the lambda of the enum constructor?

In the code below, I am trying to output the value of a symbol that is an instance variable of Operation from a PLUS constant.在下面的代码中,我试图 output 符号的值,它是来自 PLUS 常量的 Operation 的实例变量。

But I can't access that variable.但我无法访问该变量。

What's the problem?有什么问题?

public enum Operation {
    PLUS("+", (x, y) -> {
        System.out.println(symbol);
        return x + y;
    }),
    MINUS("-", (x, y) -> x - y),
    TIMES("*", (x, y) -> x * y),
    DIVIDE("/", (x, y) -> x / y);

    Operation(String symbol, DoubleBinaryOperator op) {
        this.symbol = symbol;
        this.op = op;
    }

    public String getSymbol() {
        return symbol;
    }

    protected final String symbol;
    private final DoubleBinaryOperator op;

    public double apply(double x, double y) {
        return op.applyAsDouble(x, y);
    }
}

The lambda expression is not a member of the enum , so it cannot access member variables from the enum directly. lambda 表达式不是enum的成员,因此它不能直接从enum访问成员变量。 It also has no access to protected and private members of the enum.它也无法访问枚举的protectedprivate成员。 Also, at the point where the lambda is passed to the constructor, the member variables of the enum are not in scope.此外,在将 lambda 传递给构造函数时, enum的成员变量不在 scope 中。

A possible solution is to pass symbol as a third parameter to the lambda expression, but that means you'll have to use a different functional interface than DoubleBinaryOperator .一种可能的解决方案是将symbol作为第三个参数传递给 lambda 表达式,但这意味着您必须使用与DoubleBinaryOperator不同的功能接口。

For example:例如:

interface CalculationOperation {
    double calculate(double x, double y, String symbol);
}

public enum Operation {
    PLUS("+", (x, y, symbol) -> {
        System.out.println(symbol);
        return x + y;
    }),
    MINUS("-", (x, y, symbol) -> x - y),
    TIMES("*", (x, y, symbol) -> x * y),
    DIVIDE("/", (x, y, symbol) -> x / y);

    Operation(String symbol, CalculationOperation op) {
        this.symbol = symbol;
        this.op = op;
    }

    public String getSymbol() {
        return symbol;
    }

    protected final String symbol;
    private final CalculationOperation op;

    public double apply(double x, double y) {
        return op.calculate(x, y, symbol);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM