3

I would like to know what the use of means "?" in variables.

For example, I see that I can write the code like this:

Account objAccount;
String variable = objAccount.Id;

Or write like this:

Account objAccount;
String variable = objAccount?.Id;

Thanks!

3 Answers 3

5

This is the safe navigation operator. More here

Use the safe navigation operator (?.) to replace explicit, sequential checks for null references. This operator short-circuits expressions that attempt to operate on a null value and returns null instead of throwing a NullPointerException.

Rather than the old way of writing

if (object.x != null){
  if (object.x.y != null){
    //do something with object.x.y
    Boolean yes = object.x.y;
  }
}

You can write

Boolean yes = object?.x?.y;

If either x or y are null, your variable variable will be null, but it won't generate a null pointer exception.

2

It basically returns null if instead of NullReferenceException, so

Account acc;

System.debug(acc?.Name);

will display null instead of Exception

2

? is not a valid character in a variable name. Variables must start with a letter, and can contain only letters, numbers, and underscores (_), but cannot contain more than one in a row (my__var is invalid as a variable name, but my_variable_name is acceptable). The ? is used in two features in Apex. By itself, it is used as a ternary operator (meaning, an operator that accepts three parameters), and it can be used in ?. as the Safe Navigation Operator.

In the ternary operator, we use it as a "shorthand" if statement:

Boolean someBoolean = true;
String x = someBoolean? 'Hello World': 'Goodbye World';

? must always be paired with : when used in this manner.

In the Safe Navigation Operator, we use it to make sure a variable is not null when we access a property:

Account acc;
System.debug(acc.Name); // This throws NullPointerException!
System.debug(acc?.Name); // Outputs null

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .