不兼容的类型:lambda 表达式中的错误 return 类型?

Incompatible types: bad return type in lambda expression?

给定以下代码:

/**
 * 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

我正在 运行ning 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())
        })
  });