When a method has a non-void
return type, you're responsible for ensuring that all code paths are terminated by a return
statement.
In this case, your switch
statement prescribes the return value for a specific set of logic paths, but the compiler can't guarantee that the condition will be true. You need to provide a return
statement (it can be return null;
) to ensure that a return value is provided should your condition not execute. This is true regardless of the logical construct being used (it's not unique to the switch
construct).
With switch
, you can either placeTo use a return
statement at the outermost scope of the method (aftersimple example, the entire switch
construct)following is not allowed, or you can includebecause the compiler cannot guarantee that a return value will be provided:
public static Object retVal(String input) {
switch on input {
when 'Test' {
return true;
}
}
}
This is one way to make it legal, using when else
clause to cover all casesany case not otherwise expressed inalready handled by a when
blocksblock:
public static Object retVal(String input) {
switch on input {
when 'Test' {
return true;
}
when else {
return null;false;
}
}
}
That guarantees that there will be a return value, regardless of the logical path followed and regardless of the input parameter.
Another way to deal with the issue is to place a simple return
statement after the switch
. This applies equally to other logical constructs.
public static Object retVal(String input) {
switch on input {
when 'Test' {
return true;
}
}
return false;
}