Pre-SIP: @AllowDiscard annotation to suppress -Wvalue-discard on classes and methods

I want to propose a way to suppress -Wvalue-discard and -Wnounit-statement at the definition site. Best name for the annotation I came up with is @AllowDiscard, but in Java land the more common naming is way more verbose @CanIgnoreReturnValue.

The annotation can be used

  • On classes / enums, signifying that this class is not very meaningful as a return value. Few examples are scala.js js.Dynamic, an enum containing error codes, quasi-fluent-style classes returning this in every method…
  • On methods, signifying it’s okay for the method caller to ignore the return value. Examples are various update methods that return the updated value (example from Java land ConcurrentHashMap.computeIfAbsent), or other ignorable information (for example HashMap.remove(k, v) boolean), etc..

I am not yet sure how to suppress these things on existing Java library classes.

After this, we should start thinking to make these warnings turned on by default, as they actually catch human mistakes.

Methods returning this.type never warn; the heuristic is don’t warn about discarding a reference to which I have a previous reference.

Examples such as remove returning a boolean are tricky at the use site, similarly computeIfAbsent. There is no general rule about whether the result is useful, in the sense of “new information”. The results might be of no interest just for certain instances.

I don’t know how to cope with existing Java API, but I did wonder if capture checking will let us indicate “discardability”. Then the other tiresome mechanisms become obsolete, namely -Wvalue-discard and -Wunused.

It occurs to me that “legacy” Java API may be handled as with “flex” types, discardable by default.