1

I have a very basic doubt! What does {{ }} and -> mean, and what does it mean for the following enum?

public enum BuyUsedFeatureFilters implements FeatureFilter {

    BuyUsedContext {{
        requestProperty = 
                req -> isBuyUsedContext(req);
    }};

    RequestProperty<Boolean> requestProperty;
    PropertyCondition defaultCondition = PropertyCondition.IGNORE;

    @Override
    public RequestProperty<Boolean> requestProperty() {
        return requestProperty;
    }


    private static boolean isBuyUsedContext(RequestContext requestContext){
        String buyUsedParam = requestContext.getParameters().get("buyUsedParam");

        if (StringUtils.equals(buyUsedParam, "buyUsed")) {
            return true;
        }
        return false;
    }
}
  • please refer to below posts. And let me know if any. [What is Double Brace initialization in Java?](https://stackoverflow.com/questions/1958636/what-is-double-brace-initialization-in-java) [lambda expression](https://stackoverflow.com/questions/36233477/implementing-an-interface-with-two-abstract-methods-by-a-lambda-expression/36233545#36233545) – linc01n Aug 07 '17 at 13:20
  • @linc01n Double brace initialization creates an anonymous class - here the `{{` is applied to an enum constant declaration. – assylias Aug 07 '17 at 13:21
  • This looks like pretty terrible code. Whoever wrote it should have just used a constructor. – Radiodef Aug 07 '17 at 13:22
  • 2
    @assylias Double brace initialization creates an anonymous class. And that's exactly what it does here. An anonymous class that extends the enum `BuyUsedFeatureFilters`. – Erwin Bolwidt Aug 07 '17 at 13:23
  • 1
    @assylias https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.9.1 "The optional class body of an enum constant implicitly **defines an anonymous class declaration** (§15.9.5) that extends the immediately enclosing enum type. " – Erwin Bolwidt Aug 07 '17 at 13:28
  • Thanks a lot! these answers are very helpful – Vanessa Sanchez Aug 07 '17 at 13:47

1 Answers1

2

That syntax is allowed by JLS #8.9.2 (emphasis mine):

In addition to enum constants, the body of an enum declaration may contain constructor and member declarations as well as instance and static initializers.

In your case, it's an instance initializer, which assigns a value to the requestProperty field. In your example, it is assigned a lambda expression.

assylias
  • 321,522
  • 82
  • 660
  • 783