Reputation: 968
Does IntelliJ IDEA for Java have a refactor function that can automatically move a variable definition from within a block to outside a block and refactor the definition inside the block to be a reference.
In short, turn this:
try {
IndexResponse indexResponse = elkService.post(pipelineModel);
}
Into this:
IndexResponse indexResponse = null;
try {
indexResponse = elkService.post(pipelineModel);
}
I find myself doing this quite frequently. The "surround by" refactors are smart about this in that if do NOT yet have the surrounding element (try/catch, if/then, etc.) and the code you want to surround defines variables that are used outside the surround-bound code, it will define the variable outside the block.
What I'm trying to do is refactor code where I INTRODUCE a reference outside an already-existing block.
Not the end of the world, to do this manually, but I was wondering if such a thing exists and/or if others wished for it.
Upvotes: 2
Views: 160
Reputation: 100239
Since IntelliJ IDEA 2021.3 (EAP builds are already available) it's possible just to complete the variable outside of try block to bring it into the scope:
try {
IndexResponse indexResponse = elkService.post(pipelineModel);
}
catch(Exception exception) {}
inde|
Just start typing the variable name, then invoke the completion explicitly (with Ctrl+Space), and it will be brought into the scope automatically:
IndexResponse indexResponse = null;
try {
indexResponse = elkService.post(pipelineModel);
} catch (Exception exception) {
}
indexResponse
Disclosure: I'm IntelliJ IDEA developer responsible for implementation of this feature.
Upvotes: 5
Reputation: 26492
What I do is I just reference the variable outside of the block. This will of course be highlighted as an error. I can then type Alt+Enter on the error and invoke the Bring 'X x' into scope
quick-fix, which will move the variable definition, but leave the assignment.
Upvotes: 1