Eun
Eun

Reputation: 4178

Java: Initialize condition in If construct (performance)

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
}

Upvotes: 0

Views: 93

Answers (3)

Marko Topolnik
Marko Topolnik

Reputation: 200158

I suggest leveraging the Optional API:

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

Note: Optional was introduced in Java 8.

Upvotes: 1

Ankur Shanbhag
Ankur Shanbhag

Reputation: 7804

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)

Upvotes: 2

Kent
Kent

Reputation: 195059

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

Upvotes: 3

Related Questions