2

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?

  • Are you trying to define method inside method? – Smit Jul 24 '13 at 23:36
  • 1
    @Smit i don´t think so: he is just calling a function for which he inline creates obejcts and calls member functions of them. – luk2302 Jul 24 '13 at 23:37
  • jQuery has spoiled me. ;) must.put.everything...INLINE! –  Jul 24 '13 at 23:39
  • 1
    If you use an IDE, it would be able to auto-correct this error for you. – Peter Lawrey Jul 24 '13 at 23:49
  • 1
    If your Map really contains just one key and one value, you could also do `new JSONSerializer().serialize(Collections.singletonMap(key, value))`. – VGR Jul 24 '13 at 23:56
  • [Every time someone uses double-brace initialisation, a kitten gets killed](http://stackoverflow.com/a/27521360/521799) – Lukas Eder Dec 17 '14 at 08:52

2 Answers2

3

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"?

Community
  • 1
  • 1
Jeffrey
  • 44,417
  • 8
  • 90
  • 141
  • bingo. genius. i tried it inside the initialization which gave even more errors. didn't think to do it to the parameters. thx! –  Jul 24 '13 at 23:38
1

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.);
            }}
        )
    );
}
morgano
  • 17,210
  • 10
  • 45
  • 56