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()));
}
}
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());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With