返回封闭开关表达式之外

Mat*_*aun 7 java switch-statement java-12 java-13

我在Java 12中使用开关表达式¹将字符串转换为HTTP方法

static Optional<RequestMethod> parseRequestMethod(String methodStr) {
    return Optional.ofNullable(
          switch (methodStr.strip().toUpperCase(Locale.ROOT)) {
              case "GET" -> RequestMethod.GET;
              case "PUT" -> RequestMethod.PUT;
              case "POST" -> RequestMethod.POST;
              case "HEAD" -> RequestMethod.HEAD;

              default -> {
                  log.warn("Unsupported request method: '{}'", methodStr);
                  return null;
              }
          });
}
Run Code Online (Sandbox Code Playgroud)

我想警告默认分支中不支持的方法,并返回null(然后包装在Optional中)。

但是上面的代码会导致编译器错误:

返回封闭开关表达式之外

我该如何进行编译?


为了完整起见,这是RequestMethod枚举的定义:

enum RequestMethod {GET, PUT, POST, HEAD}
Run Code Online (Sandbox Code Playgroud)

¹ 开关表达式是Java 12中的预览功能。

Mat*_*aun 12

使用yieldJava中13

在Java 13中,开关表达式使用新的受限标识符yield¹从一个块返回一个值:

return Optional.ofNullable(
        switch (methodStr.strip().toUpperCase(Locale.ROOT)) {
            case "GET" -> RequestMethod.GET;
            // ... rest omitted

            default -> {
                log.warn("Unsupported request method: '{}'", methodStr);
                // yield instead of return
                yield null;
            }
        });
Run Code Online (Sandbox Code Playgroud)

使用breakJava中12

在Java 12中,开关表达式用于break从块中返回值:

return Optional.ofNullable(
        switch (methodStr.strip().toUpperCase(Locale.ROOT)) {
            case "GET" -> RequestMethod.GET;
            // ... rest omitted

            default -> {
                log.warn("Unsupported request method: '{}'", methodStr);
                // break instead of return
                break null;
            }
        });
Run Code Online (Sandbox Code Playgroud)

yield不是关键字,作为有益由用户skomisa指出。

  • 感谢教我:现在是时候密切观察这些Java新版本了。它们产生了意想不到的内容,这让我感到震惊。 (11认同)