PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 5, 2022

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

 November 05, 2022     enums, java, lambda     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing