Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does LongSummaryStatistics implement IntConsumer?

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

like image 414
mkjh Avatar asked Jan 02 '19 09:01

mkjh


1 Answers

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.

like image 55
Andy Turner Avatar answered Oct 02 '22 16:10

Andy Turner