Reputation:
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?
Upvotes: 2
Views: 242
Reputation: 17422
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.);
}}
)
);
}
Upvotes: 1
Reputation: 44808
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"?
Upvotes: 3