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指出。