I'm using a switch expression¹ in Java 12 to convert a string to a 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;
}
});
}
I'd like to warn about the unsupported method in the default branch and return null (which is then wrapped in an Optional).
But the code above causes a compiler error:
Return outside of enclosing switch expression
How do I get this to compile?
For completeness, here's the definition of the RequestMethod
enum:
enum RequestMethod {GET, PUT, POST, HEAD}
¹ switch expressions were introduced in Java 12 as a preview feature.
RequestMethod.valueOf(methodStr.strip().toUpperCase(Locale.ROOT))
? – Indoeuropeanbreak
,continue
, orreturn
to other contexts, other than completing normally (with a value;break value
in 12, changed toyield value
in 13) or throwing. – Dunnite