2

I'm trying to do something like this:

sObject.Custom_Field__c += myNumericVar;

But I'm using dynamic SOQL, so I can't hard-code the name of the fields. The following code works, but it's really verbose and hard to read. Is there a cleaner, easier-to-read way to do it?

sObject.put (fieldName, (Decimal) sObject.get(fieldName) + myNumericVar);
3

I think you must be requiring TYPE cast in above code i.e.

sObject.put (fieldName, ((Decimal)sObject.get(fieldName)) + myNumericVar);

The above code is good if you are using it in loop, as it saves script lines, all the above operation is done in 1 script line only. To make it more developer friendly and readable, one can change it to:

Decimal fldVal = (Decimal)sObject.get(fieldName);         
// Doing addition to save one script line 
sObject.put (fieldName, fldVal + myNumericVar);
  • Good catch w/ the Type casting; I accidentally deleted it when simplifying my code! – Benj Nov 5 '12 at 22:13
1

I don't believe so.

Dynamic APEX has it's limitations around how it encapsulates the ORM.

  • Someone stole your user ?? That's not how you regulary answer Jordan – Saariko Nov 5 '12 at 7:07
  • 2
    I honestly don't think it's possible! He was asking if there was a way to accomplish the same task in the fewer operations, and I don't believe there is. What more is there to say? How else can you dynamically assign a field-value on an sObject (even if it's guaranteed to be numeric), APEX is really strongly typed like that. Sure dynamic SOQL gives you some sense of a generic assignment but more for building dynamic assignments not letting the compiler interpret your typing. – jordan.baucke Nov 5 '12 at 7:35

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.