Sub topic 1
How Apex Handles Types
Prerequisites
This chapter assumes you know basic programming ideas: variables, expressions, and conditionals. You should also know at a high level what Salesforce objects and fields are. To run the examples, use Anonymous Apex in the Developer Console, or an IDE connected to a Salesforce org or Developer Edition org. Open the Developer Console, choose Debug, then Open Execute Anonymous Apex, and tick Open Log to see System.debug output.
Apex is strongly typed
Apex is a strongly typed language. Every variable, parameter, and return value has a type that the compiler knows before the code runs. The compiler rejects code that uses a value in a way its type does not allow. Apex also checks types when it saves code to the org, so many mistakes appear at save time and not in production.
Declarations put the type before the name:
Integer count = 5;
String name = 'Acme';
Boolean isActive = true;
System.debug(name + ' ' + count + ' ' + isActive);There is no type inference with a bare keyword like var. You always write the type. This costs a few keystrokes and gives you code that is easy to read and check.
The type families
Apex types fall into a small number of families. Later chapters cover each one in detail. This chapter gives you the map.
| Family | Examples | Notes |
|---|---|---|
| Primitives | `Integer`, `Long`, `Double`, `Decimal`, `String`, `Boolean`, `Date`, `Datetime`, `Time`, `Id`, `Blob` | Hold a single simple value. |
| Collections | `List`, `Set`, `Map` | Hold many values of other types. |
| SObjects | `Account`, `Contact`, `MyObject__c`, generic `SObject` | Represent database records. |
| Enums | `Season` | A fixed set of named values. |
| Classes and interfaces | Your own classes, system classes such as `Database` | Custom and built-in behavior. |
| Object | `Object` | The parent of all types. |
Every type, including primitives, can be assigned to a variable of type Object. That makes Object useful when you do not know a value's type ahead of time. You then cast the value back to a specific type, which a later chapter covers.
Value semantics and reference semantics
Types differ in what happens when you assign one variable to another.
Primitives are passed by value. Assigning copies the value, and later changes to one variable do not affect the other. Collections, SObjects, and class instances behave differently. Assigning one to another variable copies a reference to the same underlying object, so both variables see changes.
List<Integer> first = new List<Integer>{ 1, 2, 3 };
List<Integer> second = first;
second.add(4);
System.debug(first.size());
Integer a = 1;
Integer b = a;
b = 2;
System.debug(a);The first System.debug prints 4 because first and second point at the same list. The second prints 1 because b is an independent copy of a.
One exception to know about: String is a reference type in the underlying runtime, but strings are immutable. Methods such as toUpperCase() return a new string and never change the original, so in practice strings behave like primitives.
Static and dynamic checking
Most type checks happen at compile time. The compiler checks that a List<Integer> receives only integers, and that a method called on an Account exists on Account.
Some checks happen only at run time. Casting from Object or from the generic SObject to a specific type compiles even if the cast turns out to be wrong. The failure appears as a System.TypeException when the line runs.
Object value = 'text';
try {
Integer wrong = (Integer) value;
System.debug(wrong);
} catch (System.TypeException e) {
System.debug('Cast failed: ' + e.getMessage());
}The compiler accepts the cast because an Object could hold an Integer. At run time the value is a String, so the cast throws.
Case insensitivity
Apex is case-insensitive for identifiers and keywords. Integer, integer, and INTEGER all name the same type, and count and Count name the same variable. Declaring both in one scope is a compile error. Follow the community convention anyway: type names start with a capital letter, and variable names use camelCase.
String comparison with == is also case-insensitive, which surprises developers from other languages. The strings chapter covers this.
Null is part of every type
Any variable of a reference-style type can hold null, meaning no value. A variable declared without an initializer starts as null.
String note;
System.debug(note == null);
Integer total = null;
System.debug(total == null);Primitive types in Apex are not like Java's int. An Integer variable can be null, and using a null Integer in arithmetic throws a System.NullPointerException. Check for null before you operate on a value that might lack one. A later chapter covers ?. and ??, which make this easier.
Types in the Salesforce platform
Apex types connect directly to the platform. Field types on objects map to Apex types: a Number field with zero decimal places maps to Integer or Long, a Currency field maps to Decimal, a Checkbox maps to Boolean, and a Text field maps to String. A lookup or record identifier maps to Id.
You can see the mapping by reading a field into a typed variable:
Account acc = new Account(Name = 'Acme', NumberOfEmployees = 50);
String accName = acc.Name;
Integer staff = acc.NumberOfEmployees;
System.debug(accName + ' has ' + staff + ' employees');Assigning a field to a variable of the wrong type fails to compile. For example, Boolean flag = acc.Name; is rejected because a String cannot become a Boolean.
How the pieces fit
Common errors
- Missing type on a declaration. Writing
count = 5;without declaringcountgives a "Variable does not exist" error. Declare the type first. - Incompatible assignment.
Integer x = 'five';fails with "Illegal assignment from String to Integer". - Null arithmetic.
Integer total; total = total + 1;throws aNullPointerExceptionbecausetotalisnull. Initialize numbers to0. - Wrong cast. A cast from
Objectthat compiles can still throwTypeExceptionat run time. - Shared references. Changing a list through one variable changes it through every variable that points to it. Use
new List<Integer>(first)to make a separate copy.
List<Integer> original = new List<Integer>{ 1, 2, 3 };
List<Integer> copy = new List<Integer>(original);
copy.add(4);
System.debug(original.size());
System.debug(copy.size());This prints 3 and then 4, since copy is a new list.
Exercises
Exercise
Why does Integer total; total = total + 1; fail at run time, and how do you fix it?
Show answer
An uninitialized Integer is null, and adding to null throws a System.NullPointerException. Initialize it with Integer total = 0; before adding.
Exercise
You have List<Integer> a = new List<Integer>{ 1 }; and List<Integer> b = a;. After b.add(2);, what is a.size(), and how would you have kept a unchanged?
Show answer
a.size() is 2, because a and b refer to the same list. Create a separate copy with List<Integer> b = new List<Integer>(a);.
Exercise
A cast such as (Integer) someObject compiles but fails when run. What exception does it throw, and why was it not caught at compile time?
Show answer
It throws System.TypeException. The compiler only knows the variable is an Object, which could hold an Integer, so it allows the cast. The actual value is checked when the line runs.