2

Background

I am getting this error:

Invalid conversion from runtime type String to Double

On this line of code:

line.put(targetField, (Double)fieldValue); 

The variable fieldValue is of type String and contains the value 4

The variable targetField is of type String and contains the value QUANTITY

The above code is trying to set of the value of 4 on the QUANTITY field of the QuoteLineItem object.

Questions

  1. Why is my cast not working in this QuoteLineItem.QUANTITY field?
  2. How can I successfully cast the String?

1 Answer 1

11

If you are going to cast a variable, you’re most likely doing what’s known as a downcast. This means that you’re taking the Object and casting it into a more “specific” type of Object. Here’s an example:

Object aSentenceObject = 'This is just a regular sentence';
String aSentenceString = (String)aSentenceObject;

also you can use "upcast"

String aSentenceString = 'This is just another regular sentence';
Object aSentenceObject = (Object)aSentenceString;

as you can see from example, for doing casting you have to have inheritance between classes. Double and String don't have such inheritance.


use Double.valueOf method

line.put(targetField, Double.valueOf(fieldValue)); 
1
  • Great. Thank you for updating your answer with the explanation of why :)
    – Robs
    Commented Oct 1, 2018 at 11:21

You must log in to answer this question.

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