Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does lambda expression work as an implementation of abstract method of interface?

The lambda expression below:

    new Thread(() -> 
        doSomething()
    ).start();
  1. Does the lambda expression () -> doSomething() implement the public abstract void run();?
  2. Would (param1, param2) -> {} work in the cases where an interface has only one method with two parameters?
  3. What to do with interfaces with two abstract methods using lambda expressions?

Thanks for anyone who can help me.

like image 395
stanleyerror Avatar asked Jun 08 '26 17:06

stanleyerror


2 Answers

  1. Does the lambda expression () -> doSomething() implement the public abstract void run();?

Yes, the lambda is desugared into an anonymous type which implements Runnable with the code supplied using the lambda syntax.

  1. Would (param1, param2) -> {} work in the cases where an interface has only one method with two parameters?

Yes, it is important that the lambda shape matches the shape of the interface method.

  1. What to do with interfaces with two abstract methods using lambda expressions?

You can't use lambdas directly here, but a typical workaround is to define a concrete class implementing the interface, and its constructor taking two lambdas of the appropriate shape. The implementation methods in the class delegate to these lambda objects.

like image 195
Marko Topolnik Avatar answered Jun 11 '26 07:06

Marko Topolnik


  1. Your lambda expression behaves like an abstract class instance that implements Runnable, but it's not necessarily implemented as an abstract class instance.

  2. Yes.

  3. A lambda expression cannot be used where an interface with more than one abstract method is expected. A lambda expression can only be used where a functional interface is required, which means a single abstract method.

like image 38
Eran Avatar answered Jun 11 '26 07:06

Eran