Issue
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.
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);
}
}
Solution
The lambda expression is not a member of the enum
, so it cannot access member variables from the enum
directly. It also has no access to protected
and private
members of the enum. Also, at the point where the lambda is passed to the constructor, the member variables of the enum
are not in 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
.
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);
}
}
Answered By - Jesper Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.