[SalesForce] SObject constructor signature

when instantiating an SObject type, I can set initial field values by passing them to the constructor. For example like this:

Account a = new Account(name = 'Acme', billingcity = 'San Francisco');

I'm wondering what exactly, in terms of Apex language primitives, is name = 'Acme', billingcity = 'San Francisco' in that example. In other words, what is SObject's constructor method signature? The docs are not very helpful on this topic.

Staring at the example above, knowing that variable = expression is a common syntax for assignment and that assignments often return the assigned value, my initial guess would be that – in this case – the constructor receives two String arguments, 'Acme' and 'San Francisco'. However, that is obviously not the case.

Semantically the argument(s) also resemble a Map literal, but the syntax does not match. Closer, but still no cigar.

To put my question in practical context, try building the constructor argument(s) dynamically, eg. from an arbitrary Map.

Best Answer

This is a named parameter language feature that is only supported for specific SObject types and nowhere else in Apex. It makes code where you want to assign several values cleaner - see this example. Agreed that the documentation isn't good on this.

If you want to initialise from a map, you have to write your own utility method such as:

public void someMethod() {
    ...
    Account a = (Account) init(new Account(), new Map<SObjectType, Object> {
            Account.Name => 'Acme',
            Account.BillingCity => 'San Francisco'
            });
    ...
}

private SObject init(SObject sob, Map<SObjectField, Object> values) {
    for (SObjectField field : values.keySet()) {
        sob.put(field, values.get(field));
    }
    return a;
}

that makes use of SObject.put(SobjectType, Object).

You can also use strings as the keys (though you lose the compile-time checking that the field names are valid) as there is also SObject.put(String, Object).

Related Topic