Why does LongSummaryStatistics implement IntConsumer?

  • A+

Why does LongSummaryStatistics implement IntConsumer when there is IntSummaryStatistics which also implements IntConsumer?


LongSummaryStatistics implements IntConsumer in order that it can accept int values as well as long values.

For example, this allows you to pass it to a method requiring an IntConsumer in order to consume some int data abstractly:

LongSummaryStatistics lss = new LongSummaryStatistics(); someMethod(lss);  void someMethod(IntConsumer consumer) { ... } 

There's no real reason why a LongSummaryStatistics shouldn't be usable for this purpose: int can always be widened to long without loss. However, the type system wouldn't allow lss to be used as a parameter to someMethod unless LongSummaryStatistics implemented IntConsumer directly.

True, you could do this without implementing the interface, using a lambda:

someMethod(i -> lss.consume(i)); 

but it's just a bit neater to use the reference directly.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: