Search code examples
javanetbeansjava-8functional-interfacenetbeans-11

incompatible types: Object is not a functional interface netbeans-11 java


I'm quite new to lambda expression of Java 8

I tried the following and get compile error

class Test{
    static interface MySupplier {

        Object supply();
    }

    public static void main(String[] args) {
        Object v = value();
        if (v instanceof MySupplier) {
            v = ((MySupplier) v).supply();
        }
        System.out.println(v);
    }

    static Object value() {
//        return () -> "this line will NOT get compiled."; //Error: incompatible types: Object is not a functional interface ???
//        return (Object)(() -> "this line will NOT get compiled, too."); //Error: incompatible types: Object is not a functional interface ???
        return new MySupplier() {

            public Object supply() {
                return "using inner class will work but lambda expression it not";
            }
        };

    }
}

my question is "could it be possible to use lambda expression as normal object. I want to do some thing like

    static Object value(Object v) {
        if (v instanceof MySupplier) {
            return ((MySupplier) v).supply();
        }
        return v;
    }

    public static void main(String[] args) {
//        if some case
        Object v1 = value("value 1");
        // else if some other case
        Object v1 = value(() -> { 
            //do some stuff
            return "value 2";
        });
    }

I did a lot of search but no luck. Is there any workaround? thanks in advance!


update: after having better understanding about lambda expression, the problem is how to let the compiler know the target-type of lambda expression to compile to. so the answer from ernest_k could be improve as

return (MySupplier) () -> "this line will work";

Solution

  • You can't directly return your lambda expression like that. This is because a lambda expression's target type must be a functional interface.

    You are currently creating your lambda expression in the context of a method's return statement, which means that the type of the lambda expression is that method's return type. This is not allowed:

    Object supplier = () -> "this line will get COMPILE-ERROR. -> ?????????"; //NO
    

    That's because the target type (Object) is not a functional interface. It's for the same reason that this is not allowed

    static Object value() {
        return () -> "this line will get COMPILE-ERROR. -> ?????????"; //No
    }
    

    If you really want to do what you are trying to do, which is something you should avoid, you can do it indirectly:

    static Object value() {
        MySupplier mySupplier = () -> "this line will get COMPILE-ERROR. -> ?????????";
        return mySupplier;
    }
    

    But you should not need to do this, and having MySupplier as the return type makes this code clean.