Incompatible types: bad return type in lambda expression?
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())
})
});
BJ Dela Cruz
I am a software developer and cybersecurity professional with 8+ years of industry experience. My main interests are mobile and web development, cloud computing, and cybersecurity.
Updated on June 06, 2022Comments
-
BJ Dela Cruz almost 2 years
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?