[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 boolean

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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap