0

I am looking for a possibility to initiate a variable in the if condition, so it is only valid in the scope of the condition.

Example: I want to transform this:

String tmp;
if ((tmp = functionWithALotOfProcessingTime()) != null)
{
    // tmp is valid in this scope
    // do something with tmp
}
// tmp is valid here too

Into something similar like this:

if ((String tmp = functionWithALotOfProcessingTime()) != null)
{
    // tmp is *ONLY* in this scope valid
    // do something with tmp
}
3
  • That's just not how Java's scoping rules are defined. Commented Dec 8, 2014 at 10:29
  • The compiler will automatically limit the scope of a variable to where it is used. BTW This has no impact on performance, only only limiting the use of a variable to where it is intended to be used. Commented Dec 8, 2014 at 10:42
  • There are no performance issues involved in this question. Commented Dec 8, 2014 at 10:47

3 Answers 3

3

I can think of two ways to do it:

  • You need an extra scope, {...} or try{...}catch... and declare the tmp in that scope.

  • wrap your if logic in a private method, and declare the tmp in the method, so that in your main logic, you cannot access tmp

Sign up to request clarification or add additional context in comments.

Comments

2

Try something like this:

{
    /*
     * Scope is restricted to the block with '{}' braces 
     */
    String tmp; 
    if ((tmp = functionWithALotOfProcessingTime()) != null) {
        // tmp is valid in this scope
        // do something with tmp
    }
}

tmp = "out of scope"; // Compiler Error - Out of scope (Undefined)

4 Comments

I don't want an extra scope, it messes up the readability of the code
In that case, its not doable with if blocks. Scope is just an alternative.
@Eun You clearly want an extra scope, and in Java you do it with the braces.
Accepted, since it is the closest answer, btw I know what I want and what I don't.
1

I suggest leveraging the Optional API:

Optional.ofNullable(functionWithALotOfProcessingTime()).ifPresent(tmp -> {
   // do something with tmp
});

Note: Optional was introduced in Java 8.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.