Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8: Lambda expression not expected here

Tags:

lambda

java-8

I am trying to learn Java8 and have tried following example.

I am getting a compilation error for this code. Can you please help me to resolve this issue.

public class Lambdas {

    public static void main(String[] args) {
        System.out.println("Result Of Comparision" + () -> Integer.compare("First".length(), "Second".length()));
    }
}
like image 987
Babaprakash Dabbara Avatar asked Oct 17 '25 16:10

Babaprakash Dabbara


1 Answers

a lambda expression must have a target type that is a functional interface.

A lambda expression is compatible in an assignment context, invocation context, or casting context with a target type T if T is a functional interface type (§9.8) and the expression is congruent with the function type of the ground target type derived from T.

you can make your code compile by cast lambda expression to a special functional interface. e.g: IntSupplier.

class Lambdas {

    public static void main(String[] args) {
        System.out.println("Result Of Comparision" 
        + (IntSupplier)() -> Integer.compare("First".length(), "Second".length()));
    }
}

But then print lambda itself not the result you expected. so you need call the functional interface method to get the result.

class Lambdas {

    public static void main(String[] args) {
        System.out.println("Result Of Comparision" 
         + ((IntSupplier)() -> Integer.compare("First".length(), "Second".length()))
         .getAsInt());
    }
}
like image 98
holi-java Avatar answered Oct 19 '25 11:10

holi-java



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!