Write Cleaner Code by Using Multiline Strings

Declare Apex strings that span multiple lines without using repeated string concatenation. To interpolate values into regular and multiline strings, use the new String.template() instance method instead of the existing String.format() static method. These features make your Apex code easier to write, read, and maintain, especially when you construct HTTP payloads and other large text blocks.

Where: This feature is available in all API versions. This feature applies to Lightning Experience and Salesforce Classic in Enterprise, Performance, Unlimited, and Developer editions.

Why: Unlike String.format(), which relies on index-based placeholders, String.template() uses named variable placeholders with the ${variableName} syntax. You can map values directly to descriptive keys, which eliminates the need to track array indices and makes your code easier to audit and maintain.

How: To create a multiline string, surround a text block with three single quotes ('''). After the opening quotes, start the main text on a new line. Place the closing quotes either directly after the main text or on a new line.

String newCustomerJson = '''
{
    "Name" : "John Doe",
    "Type" : "New Customer",
    "Interests": 
        [
            {"id": "101", "sportName: "biking"},
            {"id": "102", "sportName: "running"},
            {"id": "103", "sportName: "football"}
        ]
}''';

To perform string interpolation, declare a string with named variables in the format ${variableName}. Then call String.template(Map<String, Object> valueMap) on the string. Pass a map where the keys are the variables defined in the string, and the values are the corresponding substitutions for those variables.

String formatted = '''
{
    "Account": "${accountName}",
    "Last Updated": "${date}"
}'''.template(new Map<String, Object> {
            'accountName' => 'My Account',
            'date' => DateTime.newInstance(2018, 11, 15)
});
Assert.areEqual('''
{
    "Account": "My Account",
    "Last Updated": "2018-11-15 08:00:00"
}''', formatted);