Find your content:

Search form

You are here

Is there a simple way to convert any value direct to String in production code?

 
Share

When I do a System.debug(whatever), SFDC doesn't care whether whatever is a String, a Date, a Datetime, a Boolean, etc... it just makes a string of it and dumps it in the log.

But in the following code:

    private static String transverse  (Case countryCase, String csvFieldName) {
SObject      currentSObject = countryCase;
String       fieldPath      = csvFieldName;

while (fieldPath.contains('.'))
{
    List<String> pathPartList   = fieldPath.split ('[.]', 2);

                 currentSObject = (SObject) currentSObject.getSobject(pathPartList[0]);
                 fieldPath      = pathPartList[1];
}

return (String) currentSObject.get(fieldPath);

SFDC will complain if the value is a Boolean, Date, Datetime, or maybe others(?).

I imagine that with some mapping and other complexity, I could first check the field type for currentSObject.get(fieldPath) and do some transformation/formatting before returning it... but that seems to be over-complicating things.

Is there any way to just dumping the value as if I were doing a System.debug()?


Attribution to: Brian Kessler

Possible Suggestion/Solution #1

Note: I found that with String.valueOf it would return scientific notation for a large decimal value... which I didn't like (caused issues for me) -- so I implemented the following code:

public static String getStringValue (Object theObj) {
    String strValue = String.valueOf( theObj );
    if ( theObj instanceof Decimal ) strValue = ((Decimal)theObj).toPlainString(); // Prevent scientific notation
    return strValue;
}

Thought I would share in case this helps someone else in the future.


Attribution to: Paul N

Possible Suggestion/Solution #2

Try using

string.valueOf(variableName);

That should solve your problem.


Attribution to: crmprogdev
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/34675

My Block Status

My Block Content