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);
cnt2?.LastName != cnt1.LastName
.