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
Sourav PSourav P 

Instance Variable Clarification

Hi, I am new to Apex. I have the below doubt,
trigger ClosedOpportunity on Opportunity (after update) {
    List<task> carry=New List<task>();
    for(opportunity opp:trigger.new){
    if(opp.stagename=='Closed won'){
     task t=new task(
         whatid=opp.id,
         status='Active',
         Subject='Follow Up Opp Task',
         ActivityDate=system.today()
     ) ; 
        carry.add(t);
    }
        }
    insert carry;
}
In the above, code. Its working when i am putting "Insert carry" But not working if i want to put "Insert t", As i can see both are instances created, so why do i have to create "carry" and add "t" in that. Why not i can "insert t" directly ?
 
Best Answer chosen by Sourav P
Rishabh Goyal 18Rishabh Goyal 18
Hi Sourav, 

I assume you have a doubt that why you are not able to insert task  directly instead of list of task. If I am correct then answer for this is -

Every variable which is declared had its scope. In your example since you are declaring the task variable inside for loop , it can't be used outside for loop. Moreover the way you are adding the each task to list of task is most effective way of covering such scenariscenarios.
Hope this really helps you, do let me know for any other questions?

All Answers

Prady01Prady01
Hey there, what you asking is below.
 
trigger ClosedOpportunity on Opportunity (after update) {
    List<task> carry=New List<task>();
    for(opportunity opp:trigger.new){
    if(opp.stagename=='Closed won'){
     task t=new task(
         whatid=opp.id,
         status='Active',
         Subject='Follow Up Opp Task',
         ActivityDate=system.today()
     ) ; 
        //carry.add(t);
		insert t;
    }
        }
    //insert carry;
}

but I do advise aganist IT!!!

hope this helps!
prady01
Rishabh Goyal 18Rishabh Goyal 18
Hi Sourav, 

I assume you have a doubt that why you are not able to insert task  directly instead of list of task. If I am correct then answer for this is -

Every variable which is declared had its scope. In your example since you are declaring the task variable inside for loop , it can't be used outside for loop. Moreover the way you are adding the each task to list of task is most effective way of covering such scenariscenarios.
Hope this really helps you, do let me know for any other questions?
This was selected as the best answer
joseph nixjoseph nix
class Page {
public String pageName;
// instance variable with public access
private int pageNumber;
// instance variable with private access
}
https://www.mcdvoice.one/