I often have code like this:
protected @Nullable Value value;
public boolean hasValue() { return value != null; }
the problem with this is that when I do null checks like so:
if (!hasValue()) throw...
return value.toString();
then IntelliJ will warn me about a possible NPE
whereas
if (value != null) throw...
return value.toString();
avoids this warning.
is there a way to decorate my hasValue()
method so that IntelliJ knows it does a null check? and won't display the warning?
Intellij-Jetbrains is very clever IDE and itself suggests you way for solving many problems.
Look at screenshot below. It suggests your five ways for removing this warning:
1) add assert value != null
;
2) replace return statement with return value != null ? value.toString() : null;
3) surround with
if (value != null) {
return value.toString();
}
4) suppress inspection for this particular statement by adding commentary:
//noinspection ConstantConditions
return value.toString();
5) add at least, as earlier @ochi suggested use @SuppressWarnings("ConstantConditions")
annotation which can be used for method or for whole class.
To invoke this context menu use shortcut keys Alt+Enter
(I think they are common for all OS).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With