1

This code:

String a = null;
if (a?.startswith('0') && ('a' == 'a')) {
  System.debug('t');
}
else {
  System.debug('f');
}

produces:

System.NullPointerException: Attempt to de-reference a null object
STACKTRACE: AnonymousBlock: line 2, column 1
LINE: 2 COLUMN: 1

Why is that?

2

1 Answer 1

3

The issue is the expression a?.startswith('0') results in null, so the null pointer exception isn't that the safe navigation operator isn't working, it's because the if statement can't handle a null.

You can't have null in an if statement.

ie. It would result in:

String a = null;
if (null && ('a' == 'a')) {
  System.debug('t');
}
else {
  System.debug('f');
}

You can test this by replacing a?.startswith('0') with a?.startswith('0') == true. The following code will work as you expect it to:

String a = null;
if (a?.startswith('0') == true && ('a' == 'a')) {
  System.debug('t');
}
else {
  System.debug('f');
}
1
  • Fascinating that it works like this. I always thought that "if (expression)" was automatically expanded to "if (expression == true)", but apparently it works differently than I thought. Thnx! Commented Nov 26 at 7:24

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.