Is there a method reference for a no-op (NOP) that can be used for anything lambda?

Ben picture Ben · Apr 24, 2015 · Viewed 41.7k times · Source

This may sounds like a strange question, but is there a way to refer to a standard no-op (aka null operation, null-pattern method, no-operation, do-nothing method) method for a Lambda in Java 8.

Currently, I have a method that takes a, say, void foo(Consumer<Object>), and I want to give it a no-op, I have to declare:

foo(new Consumer<Object>() { 
  public void accept(Object o) { 
    // do nothing 
  }
}

where I would like to be able to do something like:

foo(Object::null)

instead. Does something like exist?

Not sure how that would work with multi-parameter methods -- perhaps this is a deficiency in the lambdas in Java.

Answer

fge picture fge · Apr 24, 2015

This is no deficiency.

Lambdas in Java are instances of functional interfaces; which, in turn, are abstracted to instances of Java constructs which can be simplified to one single abstract method, or SAM.

But this SAM still needs to have a valid prototype. In your case, you want to have a no-op Consumer<T> which does nothing whatever the T.

It still needs to be a Consumer<T> however; which means the minimal declaration you can come up with is:

private static final Consumer<Object> NOOP = whatever -> {};

and use NOOP where you need to.