liveBook · Manning

CheckReturnValue annotation

As explained in 100 Java Mistakes and How to Avoid Them

The CheckReturnValue annotation marks methods or program elements whose returned values should be checked by analysis tools.

@CheckReturnValue marks a method’s result as significant, so static analysis can flag calls whose value is discarded. It can annotate methods, classes, interfaces, or packages; broader placement applies the expectation to methods declared within that scope. section 2.11

String s = "Hello World!"; 
s.substring(6);     #1

BigInteger value = BigInteger.TWO; 
value.add(BigInteger.ONE);     #2

Discarding results from value-producing APIs can silently leave the original value unchanged, as with String.substring and BigInteger.add. section 2.11

Use the annotation as a focused contract, not a blanket rule:

  • Annotate APIs when ignoring their result is likely a mistake; static analysis cannot generally infer that intent for project and third-party methods. section 2.11
  • Use Error Prone’s @CanIgnoreReturnValue to override a broader requirement where discarding a result is intentional. section 2.11
  • For side-effect-free methods, @Contract(pure = true) can let IntelliJ IDEA warn about unused results. section 2.11

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Defines annotation scopes and tool-specific overrides, while noting that return-value significance cannot be inferred generally.
Examples
Contrasts ignored String.substring and BigInteger.add calls with assigned results.
What it assumes
Assumes familiarity with Java methods, return values, and annotations.
What you can do after
Configure static analysis with annotations that distinguish required results from intentionally ignored ones.
How it connects
Connects unused results with Error Prone, IntelliJ IDEA inspections, @CanIgnoreReturnValue, and @Contract.

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.