Question

I'm creating a HashMap inline with double braces inside a function:

public void myFunction(String key, String value) {
    myOtherFunction(
        new JSONSerializer().serialize(
            new HashMap<String , String>() {{
                put("key", key);
                put("value", value.);
            }}
        )
    );
}

and I'm receiving these errors:

myClass.java:173: error: local variable key is accessed from within inner class; needs to be declared final
                        put("key", key);
                                   ^
myClass.java:174: error: local variable value is accessed from within inner class; needs to be declared final
                        put("value", value);
                                     ^
2 errors

How can method parameters be inserted into an Object double brace initialized?

Was it helpful?

Solution

Declare your parameters as final:

public void myFunction(final String key, final String value)

Also, you might want to take a look at Efficiency of Java "Double Brace Initialization"?

OTHER TIPS

Compiler will complain if you use non final local variables in inner classes, fix it with this:

public void myFunction(final String key, final String value) {
    myOtherFunction(
        new JSONSerializer().serialize(
            new HashMap<String , String>() {{
               put("key", key);
               put ("value", value.);
            }}
        )
    );
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top