Why can't I assign lambda to Object?

后端 未结 2 1707
广开言路
广开言路 2020-11-29 11:07

I was trying to assign a lambda to Object type:

Object f = ()->{};

And it gives me error saying:

 The target type of thi         


        
相关标签:
2条回答
  • 2020-11-29 11:40

    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.

    0 讨论(0)
  • 2020-11-29 12:00

    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 = () -> {}; 
    
    0 讨论(0)
提交回复
热议问题