To answer the question about limiting the scope of a variable, instead of talking about automatic closing / controlling variables.
In Java, you can define closed anonymous regions with curly braces. It is very simple.
{ AwesomeClass hooray = new AwesomeClass()
The hooray variable is available only in this area, and not outside of it.
This can be useful if you are repeating variables that are temporary.
For example, each with an index. Just as the variable item closed in a for loop (i.e., available only inside it), the variable index closed in an anonymous area.
// first loop { Integer index = -1; for (Object item : things) {index += 1; // ... item, index } } // second loop { Integer index = -1; for (Object item : stuff) {index += 1; // ... item, index } }
I also sometimes use this if you don't have a for loop to provide a scope of variables, but you want to use generic variable names.
{ User user = new User(); user.setId(0); user.setName("Andy Green"); user.setEmail("andygreen@gmail.com"); users.add(user); } { User user = new User(); user.setId(1); user.setName("Rachel Blue"); user.setEmail("rachelblue@gmail.com"); users.add(user); }
Alex Sep 26 '13 at 13:34 on 2013-09-26 13:34
source share