0

I am new to Apex and cannot seem to find a solution to the error below on the last line of code. The error I get when compiling is "Method does not exist or incorrect signature: void get(Decimal) from the type List". Any help would be awesome. Thanks.

trigger LeadingCompetitor on Opportunity (before insert, before update) {

    for (Opportunity opp : Trigger.new) {
        List<Decimal> competitorPrices = new List<Decimal>();
        competitorPrices.add(opp.Competitor_1_Price__c);
        competitorPrices.add(opp.Competitor_2_Price__c);
        competitorPrices.add(opp.Competitor_3_Price__c);

        List<String> competitors = new List<String>();
        competitors.add(opp.Competitor_1__c);
        competitors.add(opp.Competitor_2__c);
        competitors.add(opp.Competitor_3__c);

        Decimal highestPrice;
        Integer highestPricePosition; 
        for (Integer i = 0; i < competitorPrices.size(); i++) {
            Decimal currentPrice = competitorPrices.get(i);
            if (highestPrice == null || currentPrice > highestPrice) {
                highestPrice = currentPrice;
                highestPricePosition = i;
            }
        }

        opp.Highest_Priced_Competitor__c = competitors.get(highestPricePosition);
        opp.Highest_Price__c = competitorPrices.get(highestPrice);
    }
}

2 Answers 2

4

You're using the wrong index variable.

    opp.Highest_Priced_Competitor__c = competitors.get(highestPricePosition);
    opp.Highest_Price__c = competitorPrices.get(highestPrice);

The second line should also be using highestPricePosition, which is an Integer- or simply assigning highestPrice directly, since you do gather that value in your loop.

Arrays are not indexed by Decimal values, which is why the method get(Decimal) does not exist.

0

Array indices are Integer values, not Decimal values. You have to explicitly convert a Decimal to an Integer because it causes data loss, something you wouldn't want to accidentally do.

Decimal a = 3.14;
Integer b = a; // If this worked, would equal 3, not 3.14!

Aside from that, do not use the List.get method. It is slower (CPU-wise), more tedious to type, and causes confusion to readers of your code (as the Map class also has a get method).

By using the more common [] notation, you get better performance, easier to understand code, and more concise code.

opp.Highest_Priced_Competitor__c = competitors[highestPricePosition];
opp.Highest_Price__c = highestPrice;

Also, notice how we already know what the highest price is; just assign it directly instead of getting it from the list.

You must log in to answer this question.

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