Can you guys please help me out here

Error: Compile Error: Duplicate variable: a at line 24 column 18

trigger accountfuels on lead (after insert){    
    if(trigger.isinsert)    {       
        List<account> a = new List <account>();
        list <contact> c = new list <contact>();        
        for(lead le : trigger.new){     
            Account acc = new account( name = le.company,                                                   

        for(account a: trigger.new){        
            Contact cn = new contact(   Accountid = acc.Name,                                               
        insert a;           
        insert c ;
  • 1
    You should try using Process Builder. This code is severely broken. You're trying to loop over trigger.new as two separate list types, for starters. You have multiple dml operations inside a loop. You are trying to perform dml operations on trigger records. This functionality can be achieved in a declarative way, which will save you from needing a deep-dive on how Apex works.
    – Adrian Larson
    May 2 '16 at 18:58
  • in addition to adrian's remarks ; using singular variable names like a for collections (like a list of Accounts) will confuse you and your successors to no end
    – cropredy
    May 2 '16 at 21:17

You're defining a list called "a" (List<account> a = new List <account>();) but later you're giving that same name to the variable you're iterating (for(account a: trigger.new){).

Change either one to a different name.


Sebastian's answer is perfectly valid and i write this to explain his answer.

Each variable in apex have a scope and its determined by scope identifier like global, public, private.

  1. Global scoped variables are visible even outside so used mostly in webservices.
  2. Public scoped variables are visible within application/package where this apex class resides.
  3. Private scoped variables are visible only within the apex class.

Variables declared without any scope are available only within its boundary.


for(Account acc: trigger.new){
   ... // acc variable have scope between { and } of for loop

So in your apex class when you declare List<Account> a after the if condition, its scope is till the end of the if's }. So when you try to use for(Account a: ...) inside your if {}, its illegal and throws error.

But if you interchange the places

for(Account a: ...){}
list<account> a = ...

its not illegal since the scope of variable a is within the for loop's {}.

Hope it helps you to understand better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.