I am trying to access an enum value inside the declaration of another enum value in the same class. Following is the way I found to get that done .
Java enum- Cannot reference a field before it is defined
which compiles just fine but since it involves a lot of formal code, I tried to replace the interface implementations with a Lambda but it doesn's compile with an error such as
Cannot reference a field before it is defined
Following is the lambda replacement I did.
package test;
public enum Baz {
yin(() -> {
return Baz.yang;//doesnt compile. ->Cannot reference a field before it is defined
}),
yang(new OppositeHolder() {
@Override
public Baz getOpposite() {
return yin;
}
}),
good(new OppositeHolder() {
@Override
public Baz getOpposite() {
return evil;//BUT THIS COMPILES JUST FINE, EVEN THOUGH IT ACCESSES evil WHICH HAS BEEN DECLARED LATER.
}
}),
evil(new OppositeHolder() {
@Override
public Baz getOpposite() {
return good;
}
});
private final OppositeHolder oppositeHolder;
private Baz(OppositeHolder oppositeHolder) {
this.oppositeHolder = oppositeHolder;
}
private static interface OppositeHolder {
public Baz getOpposite();
}
}
Is there any way I could do this with the help of lambda expressions, since I could be seeing a lot of enums in this class and i don't really want to repeat the boiler plate code.
EDIT I know that the error means that I cannot access an Enum that has been declared later. Also, I cannot really have the enum name stored as a string since that would be a maintenance nightmare for me. Also, I am curious why the example in the link compiles but mine does not.