Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I assign lambda to Object?

Tags:

java

java-8

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?

like image 716
SwiftMango Avatar asked Nov 09 '14 12:11

SwiftMango


2 Answers

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 = () -> {}; 
like image 146
Reimeus Avatar answered Sep 27 '22 21:09

Reimeus


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.

like image 38
Thiago Negri Avatar answered Sep 27 '22 20:09

Thiago Negri