5

I just noticed that Consumer doesn't have an identity() method, like java.util.function.Function has.

Yes, it would just be a hole to drop stuff into, but at least it would be completely clear that I'm not just missing some code in the brackets.

Take this contrived example:

public void applyConsumerIfExists(String key, String param) {
    Map<String, Consumer<String>> consumers = new HashMap<>();
    consumers.put("a", MyClass::myConsumer);

    // I can create my own, but that's no fun :(
    Consumer<String> identity = input -> {};
    consumers.getOrDefault(key, identity).accept(param);

    // DOESN'T WORK, since identity() doesn't exist on Consumer
    consumers.getOrDefault(key, Consumer.identity()).accept(param);
}

Question

Why doesn't Consumer hava an identity method?

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
tomaj
  • 1,570
  • 1
  • 18
  • 32
  • 4
    I wouldn't call it `identity`. `empty` or `noAction` would describe it better. – Eran Oct 20 '15 at 07:26
  • 2
    See this: http://stackoverflow.com/questions/29851525/is-there-a-method-reference-for-a-no-op-nop-that-can-be-used-for-anything-lamb – Paul Boddington Oct 20 '15 at 07:27
  • 4
    I think, [this](http://stackoverflow.com/a/26553481/4856258) Stuart Marks answer to similar question answers yours as well. – Tagir Valeev Oct 20 '15 at 07:33
  • 2
    It seems like the answer @TagirValeev found, which is actually from a core JDK developer, is the most illuminating answer possible. – chrylis -cautiouslyoptimistic- Oct 20 '15 at 07:35
  • 1
    There is no reason to create a local variable named `identity`. If you just use `consumers.getOrDefault(key, x->{}).accept(param);`, there is little, a predefined no-op action could offers, besides your “fun” aspect… – Holger Oct 20 '15 at 09:30

1 Answers1

2

Why doesn't Consumer<T> hava an identity method?

The Consumer<T> always consumes an object of type T and returns void.

If it had an .identity() method it should have consumed void and returned void, but it's not possible to consume a void and hence there's no such method.

The difference with Function<T, R> is that T and R can be the same. The Consumer<T> has a fixed result-type of void, which is not possible to be the same as the consumed type.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147