Safe Navigation Operator works a little bit strange

The code:

Contact cnt1 = new Contact(LastName = 'test');
Contact cnt2;

System.debug(cnt1.LastName);                   // <-- as expected: 'test'
System.debug(cnt2?.LastName);                  // <-- as expected: null

System.debug(cnt1.LastName != cnt2?.LastName); // <-- as NOT expected: false

Is anybody able to explain this behavior?

Added later:

and same behavior for user defined classes (not only for SObject):

class Test {
    Test(String field) {
        this.field = field;
    public String field;

Test t1 = new Test('test');
Test t2;

System.debug(t1.field);               // <-- as expected: 'test'
System.debug(t2?.field);              // <-- as expected: null

System.debug(t1.field != t2?.field);  // <-- as NOT expected: false
System.debug(t1.field == t2?.field);  // <-- as NOT expected: true
System.debug(t2?.field != t1.field);  // <-- as expected: true

System.debug(String.valueOf(cnt1.field) != String.valueOf(cnt2?.field)); // also false
System.debug('' + cnt1.field != '' + cnt2?.field);                       // as expected - true

interesting that when we use operator ‘==’ we have result true… What system try to compare in this lines?

In addition, System.assertEquals and System.assertNotEquals have compilation errors when trying to use this operator.

class B {
    string field = 'Test';
B b1 = new B(), b2;
//System.TypeException: Comparison arguments must be compatible types: String, Boolean
System.assertEquals(true, b1.field != b2?.field);


Somehow it works only in the first place of comparison operator (or when storing values to variables):

System.debug(cnt2?.LastName != cnt1.LastName); 

Parentheses also does not help. Out of curiosity I have tried to compare both sides with safe navigation operators:

Contact cnt2;
Contact cnt3;
System.debug(cnt2?.LastName != cnt3?.LastName); 

But this throws FATAL_ERROR Internal Error in Developer Console.

I think, that replacement mechanism does not work properly at this time and it is Salesforce bug.

Source : Link , Question Author : Aliaksandr Luferau , Answer Author : Mariia Illarionova

Leave a Comment