Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warnings for unused results of side-effect free methods in IntelliJ Idea

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.

like image 653
Martin Vseticka Avatar asked Dec 13 '16 07:12

Martin Vseticka


1 Answers

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.

enter image description here

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
  }
}
like image 191
Ingo Kegel Avatar answered Nov 19 '22 15:11

Ingo Kegel