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?
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.
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.
The return type of a method in which lambda expression used in a return statement must be a functional interface.
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())
})
});
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