我正在寻找在if条件中启动变量的可能性,因此它仅在条件范围内有效。
示例:我想转换它:
String tmp;
if ((tmp = functionWithALotOfProcessingTime()) != null)
{
// tmp is valid in this scope
// do something with tmp
}
// tmp is valid here too
进入类似的东西:
if ((String tmp = functionWithALotOfProcessingTime()) != null)
{
// tmp is *ONLY* in this scope valid
// do something with tmp
}
答案 0 :(得分:3)
我可以想到两种方法:
您需要额外的范围{...}
或try{...}catch...
,并在该范围内声明tmp
。
将您的if
逻辑包装在私有方法中,并在方法中声明tmp
,以便在您的主逻辑中,您无法访问tmp
答案 1 :(得分:2)
尝试这样的事情:
{
/*
* 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)
答案 2 :(得分:1)
我建议利用Optional API:
Optional.ofNullable(functionWithALotOfProcessingTime()).ifPresent(tmp -> {
// do something with tmp
});
注意:Java 8中引入了Optional。