function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Phuc Nguyen 18Phuc Nguyen 18 

Final Members error

I have an class where I have a Class level Variable
private static final Map<Id,Customer__c> CUSTOMERTEMP;

In my method
global override void bulkAfterExtended(){  
if (!CustVal.isEmpty()) {
                CUSTOMERTEMP = new Map<Id,Customer_c>([SELECT Id, Name,Status__c FROM Customer__c);
                }

When I go to deploy I get a 
"Final Memebers can only be assigned in thier declaration, init blocks,or constructor: CUSTOMERTEMP"

I have other private static final with no issue but they are not maps.  What am doing wrong?
Thanks,
P
Best Answer chosen by Phuc Nguyen 18
AnudeepAnudeep (Salesforce Developers) 
Hi P, 

As we know final variables can only be assigned a value once, either when you declare a variable or inside a constructor per documentation

You cannot assign the final static variable value other than the declaration of variable or static block. If you try to assign it, then you will get an error as "Final static variables can only be assigned in their declaration or in a static block"

To solve this issue, you need to assign like the example below I found online,
 
public class StaticFinalController
{
    // assign value for get property variable using static block.
    public static final string staticFinalVariable{get;}
    static
    {
        staticFinalVariable = 'Test Value';
    }
    // Assign value on declaration
    public static final string staticFinalVariable1 = 'Test';
 
    public StaticFinalController()
    {
      system.debug('### Final Value is:::::'+staticFinalVariable );
    }
 
}

Note: Static code blocks run before the constructor.

Let me know if this helps, if it does, please mark this answer as best so that others facing the same issue will find this information useful. Thank you