?.
is the Safe Navigation Operator (SNO), which is used to return a null safely when a NullPointerException
would occur. We can break it apart to make it easier to read:
List<custom_object_2__c> listofSettngs = this.map1
?.containsKey(custom_object__c?.workflow_status__c)
? this.map1?.get(custom_object__c?.workflow_status__c)
: new List<custom_object_2__c>();
This logic is incorrect. If the key has a null value, you won't end up with a new list. In other words, if the goal of this code is to always have a non-null result, it will fail if the map contains a null value for that key.
In addition, if this.map1?.containsKey
is true, the this.map1?.get
is unnecessarily paranoid. Alternatively, if custom_object__c
is null, then you'd be trying to retrieve the null key, which might be unintentional.
Further, null
isn't the same as false
in Apex, so if the map was null, you'll still get a NullPointerException
, because a condition must still be true or false, and not null.
The more appropriate version for this code would be:
custom_object_2__c[] listOfSettings =
this.map1?.get(custom_object__c?.workflow_status__c);
if(listOfSettings == null) {
listOfSettings = new custom_object_2__c[0];
}
If map1
cannot be null, you can skip the first SNO, and if the parameter won't be null, you can skip the second SNO. Either way, we can cut out the containsKey
, which is just a wasted check, since we're interested in making sure we don't end up with a null value after we're done.
Related answer.
partthis.map1?.containsKey(custom_object__c?.workflow_status__c)
is a condition that should go inside an IF statement