Reputation: 4178
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
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
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
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