Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incompatible types: bad return type in lambda expression?

Given the following code:

/**
 * Prints the grid with hint numbers.
 */
private void printGridHints() {
  minesweeperGrid.forEach((k, v) -> {
    v.stream().forEach(
        square -> square.isMineLocatedHere() ? System.out.print("*") : System.out.print(square
            .getNumSurroundingMines()));
    System.out.println();
  });
}

My compiler is giving me the following error:

error: incompatible types: bad return type in lambda expression

square -> square.isMineLocatedHere() ? System.out.print("*") : System.out.print(square
                                                                                ^

missing return value

I am running Gradle version 2.2, and I have JDK 8u31 installed. What's interesting that Eclipse does not show any compiler errors, even after I clean and rebuild my project, but when I run gradle build on the command line, I get this compiler error.

Why am I getting this error, and how do I fix it?

like image 630
BJ Dela Cruz Avatar asked Feb 22 '15 09:02

BJ Dela Cruz


People also ask

What is the return type of lambda expression must be compatible with which one?

The lambda expression must return a result that is compatible with the result of the functional interface method. If the result is void , the lambda body is void-compatible. If a value is returned, the lambda body is value-compatible.

Can lambda expression have return type?

The return type for a lambda is specified using a C++ feature named 'trailing return type'. This specification is optional. Without the trailing return type, the return type of the underlying function is effectively 'auto', and it is deduced from the type of the expressions in the body's return statements.

What is the return type of lambda expression question?

The return type of a method in which lambda expression used in a return statement must be a functional interface.


1 Answers

You can't have void as type for the second and third expression in a ternary expression. I.e., you can't do

.... ? System.out.print(...) : System.out.print(...)
                  ^^^^^                   ^^^^^

(If Eclipse says otherwise, it's a bug.) Use an if statement instead:

minesweeperGrid.forEach((k, v) -> {
    v.stream().forEach(
        square -> {
            if (square.isMineLocatedHere())
                System.out.println("*");
            else
                System.out.println(square.getNumSurroundingMines());
        })
  });

Or break it down as follows:

minesweeperGrid.forEach((k, v) -> {
    v.stream().forEach(
        square -> {
            System.out.println(square.isMineLocatedHere()
                    ? "*" : square.getNumSurroundingMines())
        })
  });
like image 134
aioobe Avatar answered Nov 15 '22 02:11

aioobe