Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda that does absolutely nothing

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.

like image 724
Rien Avatar asked May 07 '15 17:05

Rien


People also ask

Can lambda expression have empty body?

You can think of lambda expressions as anonymous methods (or functions) as they don't have a name. A lambda expression can have zero (represented by empty parentheses), one or more parameters. The type of the parameters can be declared explicitly, or it can be inferred from the context.

How do you return nothing in lambda Python?

Calling type(None) will return you the NoneType constructor, which you can use for doing nothing: type(None)() . Keep in mind that the NoneType constructor only takes 0 arguments. In Python 2, though, creating instances of NoneType is impossible, so lambda: None would make the most sense.

Is there a Noop in Java?

This is probably one of the simplest Java annotation processing libraries out there. It generates no-op implementations of your interfaces.

What is no-op in Java?

A no op (or no-op), for no operation , is a computer instruction that takes up a small amount of space but specifies no operation. The computer processor simply moves to the next sequential instruction.


2 Answers

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(); 
like image 63
Eddú Meléndez Avatar answered Sep 28 '22 08:09

Eddú Meléndez


The lambda expression I use now is:

() -> {} 
like image 41
Rien Avatar answered Sep 28 '22 10:09

Rien