When I don't assign result of BigDecimal.divide()
method to a variable, I get a nice warning from IntelliJ Idea:
Result of BigDecimal.divide() is ignored.
Can I somehow get the same warning for my own (side-effect free) functions? Something like assigning a Java annotation to my function.
This is the "Result of method call ignored" inspection. By default, it only reports a couple of special methods, including all methods of java.lang.BigDecimal
. In the inspection configuration you can add other classes and methods that should be reported in this way.
The "Report all ignored non-library calls" check box selects all classes in your project.
If you want to use annotations, you can annotate single methods or entire classes with the JSR 305 annotation
javax.annotation.CheckReturnValue
Since IDEA 2016.3 you can even use the error prone annotation
com.google.errorprone.annotations.CanIgnoreReturnValue
to exclude single methods from return value checking. Using both annotations, you can write a class like this:
import javax.annotation.CheckReturnValue;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
@CheckReturnValue
class A {
String a() { return "a"; }
@CanIgnoreReturnValue
String b() { return "b"; }
void run() {
a(); // Warning
b(); // No warning
}
}
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