给定以下代码:
/**
* 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();
});
}
我的编译器给我以下错误:
error: incompatible types: bad return type in lambda expression
square -> square.isMineLocatedHere() ? System.out.print("*") : System.out.print(square
^
missing return value
我正在运行 Gradle 2.2 版,并且安装了 JDK 8u31。有趣的是,Eclipse 没有显示任何编译器错误,即使在我清理并重建我的项目之后,但是当我在命令行上运行 gradle build
时,我得到了这个编译器错误。
为什么会出现此错误,我该如何解决?
最佳答案
您不能将 void
作为三元表达式中第二个和第三个表达式的类型。也就是说,你不能这样做
.... ? System.out.print(...) : System.out.print(...)
^^^^^ ^^^^^
(如果 Eclipse 另有说明,则为错误。)改用 if
语句:
minesweeperGrid.forEach((k, v) -> {
v.stream().forEach(
square -> {
if (square.isMineLocatedHere())
System.out.println("*");
else
System.out.println(square.getNumSurroundingMines());
})
});
或者分解如下:
minesweeperGrid.forEach((k, v) -> {
v.stream().forEach(
square -> {
System.out.println(square.isMineLocatedHere()
? "*" : square.getNumSurroundingMines())
})
});
关于java - 不兼容类型 : bad return type in lambda expression?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28656211/