Today I was shown a code I though could use some Safe navigation improvement, after some tries I don't understand how to apply safe navigation in this scenario with an Object that has to be converted to Decimal.

Map<String,Object> testMap =new Map<String,Object> {'field1'=>null,'field2'=>3.3};

// This has to be refactored using safe navigation
Decimal new_decimal = testMap.get('field1') != null?  ((Decimal)testMap.get('field1').set_scale(2)):null

I tried something like

Decimal new_decimal = (Decimal)testMap.get('field1')?.set_scale(2);

But I get

Method does not exist or incorrect signature: void set_scale(Integer) from the type Object

How can I get my expected result using Safe navigation?

  • Can you try to surround your cast before the safe-navigator? Decimal new_decimal = ((Decimal)testMap.get('field1'))?.set_scale(2); Oct 27 '21 at 16:29
  • I tried it, same error. Oct 27 '21 at 17:21
  • Fair enough, what about storing (Decimal) testMap.get('field1') first in a variable and then using the safe-navigator? I'm assuming this might be a corner case of safe-navigator not yet covered. Oct 27 '21 at 17:28

The way to use it is the following one

Decimal new_decimal = ((Decimal) testMap.get('field1'))?.setScale(2);

which has been suggested already. The problem is the method that you were using as set_scale() is not a method, it is setScale().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.