0

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?

3
  • Can you try to surround your cast before the safe-navigator? Decimal new_decimal = ((Decimal)testMap.get('field1'))?.set_scale(2); Commented Oct 27, 2021 at 16:29
  • I tried it, same error. Commented Oct 27, 2021 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. Commented Oct 27, 2021 at 17:28

1 Answer 1

2

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().

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .