Skip to main content
Hitesh Sharma (360 Cloud Solution) 님이 #Apex에 질문했습니다

Main Code:  

public class NewConstEx { 

public list<string> subjects; 

    public NewConstEx(list<string> subjectlist){ 

        subjects=subjectlist; 

    } 

 

anonymous Window:  

list<string> mysubject = new list<string>{ 

    'Apex', 

        'LWC', 

        'JS', 

        'Java' 

}; 

NewConstEx N = new NewConstEx(mysubject); 

system.debug(N.subjects); 

 

#Apex  #Salesforce Developer

답변 1개
  1. 8월 20일 오후 5:23

    Hi Hitesh - yes, you can define the list inside the class instead of passing it from anonymous apex. A couple of ways: 

     

    1) A no-argument constructor that builds the list itself: 

     

    public class NewConstEx { 

      public List<String> subjects; 

      public NewConstEx() { 

        subjects = new List<String>{'Apex','LWC','JS','Java'}; 

      } 

     

    // Anonymous: 

    NewConstEx n = new NewConstEx(); 

    System.debug(n.subjects); 

     

    2) Or initialize the field right at declaration (no constructor needed for that): 

    public List<String> subjects = new List<String>{'Apex','LWC','JS','Java'}; 

     

    When to use which: 

    - Parameterized constructor (your current version) = the CALLER supplies the data. Best when different callers pass different lists, so it is more reusable. 

    - No-arg constructor or field initializer = the CLASS owns the data. Best when the list is fixed/internal. 

     

    And you do not have to choose - Apex supports constructor overloading, so you can keep BOTH a no-arg and a List<String> constructor in the same class and call whichever fits. 

     

    If this helps, please mark it as the Best Answer so it helps the next person - thanks :)

0/9000