局部变量是多余的java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26436155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Local variable is redundant java
提问by collint25
Can someone explain to me why it's giving me "local variable is redundant error"?
有人可以向我解释为什么它给我“局部变量是冗余错误”?
public double depreciationAmount() {
double depreciationAmount = (cost * percentDepreciated);
return depreciationAmount;
}
采纳答案by Stephen C
Can someone explain to me why it's giving me "local variable is redundant error"?
有人可以向我解释为什么它给我“局部变量是冗余错误”?
Because you can trivially write this without using a local variable.
因为您可以在不使用局部变量的情况下轻松编写它。
public double depreciationAmount() {
return cost * percentDepreciated;
}
Hence the local variable is unnecessary / redundant.
因此局部变量是不必要的/多余的。
However, I surmise that this is NOT a compiler error. It might be a compiler warning, or more likely it is a style checker or bug checker warning. It is something you could ignore without any risk to the correctness of your code ... as written.
但是,我推测这不是编译器错误。它可能是一个编译器警告,或者更有可能是一个样式检查器或错误检查器警告。这是您可以忽略的东西,而不会对您的代码的正确性造成任何风险……正如所写的那样。
Also, I would predict that once that the code has been JIT compiled (by a modern Hotspot JIT compiler ...) there would be no performance difference between the two versions.
另外,我预测一旦代码被 JIT 编译(通过现代 Hotspot JIT 编译器......),两个版本之间不会有性能差异。
回答by dramzy
You only use the value of percentDepreciated to return it when you could have just did return (cost * percentDepreciated)
您只使用percentDepreciated 的值在您本可以这样做时返回它 return (cost * percentDepreciated)
回答by seekingStillness
Although not the case here, if having redundant local variable is desired (I've had one time where this was the case - without getting into specifics), here's how to suppress this specific warning.
虽然这里不是这种情况,但如果需要有冗余的局部变量(我曾经有一次是这种情况 - 没有详细说明),这里是如何抑制这个特定警告。
@SuppressWarnings("UnnecessaryLocalVariable")
public double depreciationAmount() {
double depreciationAmount = (cost * percentDepreciated);
return depreciationAmount;
}