【发布时间】:2019-11-10 09:53:43
【问题描述】:
我在 Java 12 中使用 switch 表达式¹将字符串转换为 HTTP method:
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;
}
});
}
我想警告默认分支中不支持的方法并返回 null(然后将其包装在 Optional 中)。
但是上面的代码会导致编译错误:
在封闭的 switch 表达式之外返回
如何编译?
为了完整起见,这里是 RequestMethod 枚举的定义:
enum RequestMethod {GET, PUT, POST, HEAD}
¹ switch expressions 在 Java 12 中作为预览功能引入。
【问题讨论】:
-
为什么不使用
RequestMethod.valueOf(methodStr.strip().toUpperCase(Locale.ROOT))? -
@VGR:因为这会引发 IllegalArgumentException。但问题中的代码只是显示编译器错误“返回封闭开关表达式之外”如何发生的示例。
-
表达式(包括 switch 表达式)必须要么产生一个值,要么抛出。你不能
break、continue或return到其他上下文,除了正常完成(使用值;break value在 12,更改为yield value在 13)或投掷。
标签: java switch-statement java-12 java-13