I was trying to assign a lambda to Object type:
Object f = ()->{};
And it gives me error saying:
The target type of this expression must be a functional interface
Why is this happening, and how to do this?
It's not possible. As per the error message Object
is not a functional interface, that is an interface with a single public method so you need to use a reference type that is, e.g.
Runnable r = () -> {};
This happens because there is no "lambda type" in the Java language.
When the compiler sees a lambda expression, it will try to convert it to an instance of the functional interface type you are trying to target. It's just syntax sugar.
The compiler can only convert lambda expressions to types that have a single abstract method declared. This is what it calls as "functional interface". And Object
clearly does not fit this.
If you do this:
Runnable f = (/*args*/) -> {/*body*/};
Then Java will be able to convert the lambda expression to an instance of an anonymous class that extends Runnable
. Essentially, it is the same thing as writing:
Runnable f = new Runnable() {
public void run(/*args*/) {
/*body*/
}
};
I've added the comments /*args*/
and /*body*/
just to make it more clear, but they aren't needed.
Java can infer that the lamba expression must be of Runnable
type because of the type signature of f
. But, there is no "lambda type" in Java world.
If you are trying to create a generic function that does nothing in Java, you can't. Java is 100% statically typed and object oriented.
There are some differences between anonymous inner classes and lambdas expressions, but you can look to them as they were just syntax sugar for instantiating objects of a type with 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