77

I needed to have a lambda expression of the functional interface Runnable that did nothing. I used to have a method

private void doNothing(){
    //Do nothing
}

and then use this::doNothing. But I've found an even shorter way to do this.

Rien
  • 1,596
  • 1
  • 12
  • 16

3 Answers3

97

For Runnable interface you should have something like that:

Runnable runnable = () -> {};

Where:

  • () because run method doesn't receive args
  • {} body of run method which in this case is empty

After that, you can call the method

runnable.run();
Neuron
  • 5,141
  • 5
  • 38
  • 59
Eddú Meléndez
  • 6,107
  • 1
  • 26
  • 35
  • For those of us who want a strongly typed in the spirit of the `@FunctionalInterface`, here's the equivalent : https://stackoverflow.com/a/76985309/501113 – chaotic3quilibrium Aug 28 '23 at 17:50
52

The lambda expression I use now is:

() -> {}
Rien
  • 1,596
  • 1
  • 12
  • 16
  • We had hundreds of these throughout our codebase. It makes refactoring the legal code base frustrating. I reified this pattern with this: https://stackoverflow.com/a/76985309/501113 – chaotic3quilibrium Aug 28 '23 at 17:51
16

Guava - Runnables.doNothing();

Neuron
  • 5,141
  • 5
  • 38
  • 59
emanuel07
  • 738
  • 12
  • 27
  • 8
    It's madness to include a library for a 6 character expression. Even if you already had Guava in your dependencies this solution is longer than the simple expression and does not improve readability. – Björn Zurmaar Jun 11 '20 at 21:48
  • 11
    in my opinion it does improve readibility. You do a static import and in the code you just see "doNothing()". The reader wil understand very quickly that you intentionally decided to "do nothing". Ofk adding Guava to classpath just for that would be a waste. – fascynacja Jul 03 '20 at 09:56
  • 2
    Add a comment to show you intentionally decided to do nothing. – MeanwhileInHell Aug 20 '21 at 13:42
  • What about memory allocation, will () -> {} not cause jvm to create new object each time it is invoked, unlike the doNothing which probably refers to singleton object? – Mateusz Fryc Jul 07 '23 at 11:21