Sub topic 3
What a Future Method Can Accept
This chapter assumes you can write Apex classes and static methods, work with collections, and run basic SOQL and DML. It covers the rules for what you can pass into a future method and what it can return, and the errors you see when you break them.
The rules
A future method is declared with @future. The compiler enforces these rules at save time:
- The method must be
static. - The return type must be
void. - Parameters must be primitives, arrays of primitives, or collections of primitives.
Primitives include Integer, Long, Decimal, Double, Boolean, String, Date, Datetime, and Id. Collections that hold them, such as List<String>, Set<Id>, and Map<Id, String>, are accepted.
You cannot pass sObjects or custom Apex class instances. You also cannot pass collections of sObjects, such as List<Account>.
Why these rules exist
A future method does not run when you call it. Salesforce stores the call, including its arguments, in a queue. The method runs later in a separate transaction, possibly minutes afterward.
If you could pass a whole Account, its field values would be a snapshot. By the time the method runs, another user or process may have changed the record. Restricting arguments to primitives keeps the saved call simple and avoids acting on stale data.
Valid and invalid signatures
These signatures compile:
public class ParameterExamples {
@future
public static void withIds(Set<Id> accountIds) {}
@future
public static void withMixedPrimitives(String name, Integer count, Boolean active) {}
@future
public static void withMap(Map<Id, String> notesByAccountId) {}
}These do not compile:
public class BadParameterExamples {
// Error: sObject parameter is not allowed
@future
public static void withRecord(Account acc) {}
// Error: collection of sObjects is not allowed
@future
public static void withRecords(List<Account> accounts) {}
// Error: non-static method
@future
public void notStatic(Set<Id> ids) {}
// Error: return type must be void
@future
public static Integer withReturn(Set<Id> ids) { return 1; }
}Passing richer data
Sometimes the IDs are not enough. You may need per-record values, such as a note to apply to each account. You have two common options.
Pass a map of primitives:
public class NoteService {
@future
public static void applyNotes(Map<Id, String> notesByAccountId) {
List<Account> accounts = [
SELECT Id, Description
FROM Account
WHERE Id IN :notesByAccountId.keySet()
];
for (Account a : accounts) {
a.Description = notesByAccountId.get(a.Id);
}
update accounts;
}
}Or serialize a complex structure to a String with JSON.serialize(), then call JSON.deserialize() inside the method:
public class OrderService {
public class OrderInfo {
public Id accountId;
public Decimal amount;
}
@future
public static void processOrders(String serializedOrders) {
List<OrderInfo> orders =
(List<OrderInfo>) JSON.deserialize(serializedOrders, List<OrderInfo>.class);
for (OrderInfo info : orders) {
System.debug('Account ' + info.accountId + ' amount ' + info.amount);
}
}
}The caller builds the list and passes JSON.serialize(orders). The String parameter satisfies the compiler. Keep this for small payloads. Passing many full records as JSON brings back the stale data problem.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Compile error about parameter type | Passed an sObject or `List<sObject>` | Pass `Set<Id>` and re-query |
| Compile error about method signature | Method is not `static` or does not return `void` | Make it `public static void` |
| Method sees old field values | Values were captured at call time | Re-query inside the method |
| Cannot use return value | Future methods return nothing | Write results to records, or use Queueable Apex |
Exercise
A teammate writes @future public static void sync(List<Contact> contacts). Why does it fail, and how would you rewrite the signature and first line of the body?
Show answer
sObject collections are not allowed as future method parameters. Change the signature to @future public static void sync(Set<Id> contactIds) and start the body with List<Contact> contacts = [SELECT Id, Email FROM Contact WHERE Id IN :contactIds];. This also ensures the method works with current field values.