The lambda expression below:
new Thread(() ->
doSomething()
).start();
() -> doSomething() implement the public abstract void run();?(param1, param2) -> {} work in the cases where an interface has only one method with two parameters?Thanks for anyone who can help me.
- Does the lambda expression
() -> doSomething()implement thepublic abstract void run();?
Yes, the lambda is desugared into an anonymous type which implements Runnable with the code supplied using the lambda syntax.
- 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.
- 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.
Your lambda expression behaves like an abstract class instance that implements Runnable, but it's not necessarily implemented as an abstract class instance.
Yes.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With