[SalesForce] Primitive and complex data types in Apex

I am getting a little confused about which data types are primative and which are complex. The confusion really lies with only 1 or 2 of the data types. Below I have listed what I think is correct.

Primitive:

Blob,
Boolean,
Date,
Datetime,
Decimal,
Double,
ID,
Integer,
Long,
Object (This one causes a little confusion as I believe sObject is complex but isn't Object the superclass of Sobject?), String

Complex:

Sobject, List,
Set,
Map,
Enum

Is the above all correct? I understand that primitive data types are technically not primitive since they can be null and have methods so I am unsure what the defining characteristics are for a primitive and complex data type.

Best Answer

The distinction between primitives and non-primitives in Apex is, in my opinion, a bit fuzzier than it is in some languages. In particular, nullability and having methods does not distinguish primitives from non-primitives in Apex.

However, the documentation defines the Apex primitives as:

  • Blob
  • Boolean
  • Date
  • DateTime
  • Decimal
  • Double
  • Id
  • Integer
  • Long
  • Object
  • String
  • Time

Object, however, is a unique case insofar as it is the root of the type hierarchy in Apex (every data type is implicitly an Object, including sObjects and other primitives).

sObject itself is an abstract base class. You cannot construct a new, untyped sObject instance.

List, Set, and Map are parameterized collections. I think one can clearly define them as complex types.

enum itself is not a type; it's a keyword like class to create a new type. Enumerated types are Objects, however. If you were to do this in Anonymous Apex

public enum Test { VAL_ONE, VAL_TWO }
Test var = Test.VAL_ONE;
System.debug(var instanceof Object);

you'll get back an error saying

Operation instanceof is always true since an instance of Test is always an instance of Object

Related Topic