Friday, August 15, 2014

Invalid constructor syntax, name=value pairs can only be used for SObjects (Line: 90)


If you bumped to this entry, I would like to thank you.I 'll update the content as below.Since my explanation not really helpful at previous post.You still able to view old post at OBSOLETE section below at the end of this post.

I always accidentally face this exception : Invalid constructor syntax, name=value pairs can only be used for SObjects because I instantiate inner class like SObject such as below :

WrapperObj obj = new WrapperObj (paramId=a.Id,isChecked=a.Primary__c,Account=a);

While that only valid for SOBJECT.For inner class, we should use this.Without name value pair.

WrapperObj obj = new WrapperObj (a.Id,a.Primary__c,a);


public class MyExtension {
    
    //other code
    
    public void retrieveInfo(){
        List<WrapperObj >  listAccountObject = new List<WrapperObj > ();
        List<Account > listAccount = [Select Id,Primary__c from Account  where Id=:acct.Id];
        
        if(listAccount.size()>0){
            for(Account a: listAccount ){
        //INVALID WAY FOR CONSTRUCTOR#2
              WrapperObj obj = new WrapperObj (paramId=a.Id,isChecked=a.Primary__c,Account=a);
  
    //CORRECT WAY FOR CONSTRUCTOR#2
     WrapperObj obj = new WrapperObj (a.Id,a.Primary__c,a);
     
    //ANOTHER CORRECT WAY FOR CONSTRUCTOR#1
     WrapperObj obj = new WrapperObj ();
     obj.paramId=a.Id;
     obj.isChecked=a.Primary__c;
     obj.myAccount=a;
              
           }
  }
    }
    
 //inner class
    public class WrapperObj {
    
         public String paramId {get;set;}
         public Boolean isChecked {get;set;}
         public Account myAccount {get;set;}
         
   //CONSTRUCTOR#1
         public WrapperObj(){
  }
  
   //CONSTRUCTOR#2
         public WrapperObj (String paramId,Boolean isChecked,Account acct){
            this.paramId=paramId;
            this.isChecked=isChecked;
            this.myAccount=acct;
    
         }

    }
}

Have a nice day.

Thanks.
-------------------------------------------OBSOLETE---------------------------------------------------------
*Yawn* Sometimes the best of us always forget the basic one.

If we create inner class , it is not allowable to instantiate it like we always do for standard object as below:

Series s = new Series(name='s1');

We should instantiate and define using longer way like this:

Series s=new Series();
s.name='s1';

Good Luck~