java - 不兼容类型 : bad return type in lambda expression?

标签 java eclipse lambda java-8

给定以下代码:

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

相关文章:

java - IBM i (as400) DB2 从 java 检索并解压值

android - android galaxy的真实设备数据库文件为空点异常

java - 代码在 gingerbird 上运行成功但果冻 bean 错误 : android. os.NetworkOnMainThreadException

c++ - 默认情况下 Constexpr lambda?

java - 使用 Java 8 流处理 map 列表

java-8 在不创建新列表的情况下过滤列表

java - 如何使用 HttpURLConnection 发送请求而不处理 Java 中的响应

java - 数据库更改时 RecyclerView 不更新

java - 在多个字段上使用 groupingBy 条件后获取计数

java - 在浏览器上显示 java 代码的动态 Web 项目?