0

while following the best practices I got to know that while fetching generic sobject fields we should typecast the values so please refer the below code where I was trying to type cast to string and I got an error:

List<Sobject> accnt = [SELECT ID,Name,AnnualRevenue FROM Account WHERE Rating IN ('Hot','Cold')];
For(Sobject a : accnt){
    System.debug((String)a.get('Name')+' '+(String)a.get('AnnualRevenue'));
}

Error:

Line: 3, Column: 1 System.TypeException: Invalid conversion from runtime type Decimal to String

Annual revenue is a currency field which returns decimal values. So, could anyone explain why it is giving me an error while typecasting decimal to string? Note - >I Know that I can avoid typecasting here in this case.

2 Answers 2

3

The + is used to add two numbers together, and to concatenate String values. When you use a non-string next to a String, toString() will be called on the object. As such, you can simply say:

System.debug(a.get('Name')+' '+a.get('AnnualRevenue'));

You can't directly cast a non-String to a string, as the following is also an error:

String output = (String)1.23;

But you can use the + operator with a string on either side:

String output = ''+1.23;
String output = 1.23+'';

I often use this as a quick technique to convert most primitives to a String.

You can only use typecasting between compatible types, like a Decimal to an Integer (with precision loss) or a String to an Id.

3
  • Thanks @sfdcfox, Could also please let me know which are the other compatible types for type casting other than what you have mentioned in your answer? Jan 1 at 7:22
  • @SaiBhargav There are three basic typecasts for primitives: numeric values (Integer, Decimal, Long, Double), dates (Date, DateTime), and Strings (String, Id). You can also typecast between compatible collection types (sometimes, see this answer), as well as user-defined classes and interfaces. For most other type conversions, you'll use the appropriate valueOf methods, most of which don't accept null values as a parameter.
    – sfdcfox
    Jan 1 at 7:33
  • Thanks a lot! for the explanation Jan 1 at 8:17
0

You can avoid typecasting here. As it is not required here. Even if you want to typecast you could use String.valueOf(a.get('AnnualRevenue'))

1
  • Thanks Mukul, But I Know that I can avoid type casting here. Posted this question so i could know on how to type cast in this situation if I want to. Also String.ValueOf() Doesn't take object as parameter and a.get('AnnualRevenue') will return an object(I have already tried that as well). Jan 1 at 7:16

You must log in to answer this question.

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