In Apex, you can use variables in the value of a switch statement by defining the variable before the switch statement and using it directly in the switch expression. Here's a simple example to illustrate how to use variables in the value of an Apex switch statement:
public class SwitchExample {
public static void runSwitchExample() {
String status = 'InProgress';
switch on status {
when 'New' {
System.debug('The status is New.');
}
when 'InProgress' {
System.debug('The status is InProgress.');
}
when 'Completed' {
System.debug('The status is Completed.');
}
when else {
System.debug('The status is Unknown.');
}
}
}
}
In this example:
We define a variable status and set it to 'InProgress'.
The switch statement is used to check the value of the status variable.
Depending on the value of status, the appropriate when block is executed.
If you want to use a variable within the when condition, you can use a constant or another variable. Here’s an example using a constant:
public class SwitchExample {
public static final String STATUS_NEW = 'New';
public static final String STATUS_IN_PROGRESS = 'InProgress';
public static final String STATUS_COMPLETED = 'Completed';
public static void runSwitchExample() {
String status = 'InProgress';
switch on status {
when STATUS_NEW {
System.debug('The status is New.');
}
when STATUS_IN_PROGRESS {
System.debug('The status is InProgress.');
}
when STATUS_COMPLETED {
System.debug('The status is Completed.');
}
when else {
System.debug('The status is Unknown.');
}
}
}
}
In this example, the constants STATUS_NEW, STATUS_IN_PROGRESS, and STATUS_COMPLETED are used in the when conditions, making the code more readable and maintainable.
Remember, the switch statement in Apex can only be used with specific types of variables: Integer, Long, String, Enum, and SObjectType. Make sure your variable is of one of these types when using it in a switch statement.