@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
