Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

java - The target type of this expression must be a functional interface: Function vs Consumer

In Code 1: there are no errors and it works. The Code 2 has the mentioned compile time error.

Question 1: Why?

Question 2: How do we return a Function in Code 2?

Code 1:

static <T> Consumer<T> m1(Consumer<T> consumer) {
    Consumer<T> c = obj -> {
        consumer.accept(obj);

    };
    return c;
}

Code 2:

static <T, R> Function<T, R> m2(Function<T, R> f) {
    // Compile Error: The target type of this expression must be a functional interface
    Function<T, R> o = {x -> {
        f.apply(x);
    }};
    return o;

}
question from:https://stackoverflow.com/questions/65621369/the-target-type-of-this-expression-must-be-a-functional-interface-function-vs-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In code 2, I get your error in Eclipse, which is not helpful. When compiling on the command line, I get this error:

J.java:28: error: illegal initializer for Function<T,R>
                Function<T, R> o = {x -> {
                                   ^
  where T,R are type-variables:
    T extends Object declared in method <T,R>m2(Function<T,R>)
    R extends Object declared in method <T,R>m2(Function<T,R>)
J.java:28: error: lambda expression not expected here
                Function<T, R> o = {x -> {
                                    ^
2 errors

Your braces are unnecessary. The outer pair of braces is attempting to create an array initializer, not a lambda expression. The inner braces does attempt to create a lambda expression, but that can't be done within an array initializer.

You can have an expression be the return type of a lambda expression, without any braces. Try:

Function<T, R> o = x -> f.apply(x);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...