[Java] Bad return type in lambda expression: int cannot be converted to boolean


If you are using functional interface using Lambda expression in your code and you get the below error, that's because your expression does not return the datatype which the Function Interface method expects,

Example: Functional Interface
package org.code2care;

@FunctionalInterface
public interface Validate {

    public boolean isString(Object object);

}
Example: Lambda expression
package org.code2care;

public class Example {

    public static void main(String[] args) {

        Validate validate = object -> object.toString();
        Validate validate1 = object -> object.toString().length();

        System.out.println(validate.isString("Java"));
    }
}
Error:

/Users/code2care/IdeaProjects/examples/src/org/code2care/Example.java:7:54
java: incompatible types: bad return type in lambda expression
   java.lang.String cannot be converted to boolean|

/Users/code2care/IdeaProjects/examples/src/org/code2care/Example.java:7:58
java: incompatible types: bad return type in lambda expression
   int cannot be converted to booleanHBE|

As you can see the reason for the complication error is isString(Object obj) returns a boolean and not java.lang.String or an int

Java - Bad return type in lambda expression - String or int cannot be converted to boolean

Top Hashtags:

Advertisements

Advertisements




Advertisements