[SalesForce] simple way to convert any value direct to String in production code

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

Best Answer

The String class has several static utility methods to transform a value into its string representation, like this:

String.valueOf(variableName);

That should solve your problem.

Related Topic