+ Start a Discussion
Kogila KenneyKogila Kenney 

Class and Methods

Hi
I am new to Salesforce, trying to understand classes and methods.When I complied the below code it give the below error.

public class Myhelloworld
{
    public static void applyDiscount(Book__c[] books)
    {
        for(list<Book__c[]> b:Books)
    {
    b.Price__c *=0.9;
    }
  
Error: Compile Error: Initial term of field expression must be a concrete SObject: List<List<Book__c>> at line 7 column 5

Thanks
K.Kogila
Best Answer chosen by Kogila Kenney
Jithin Krishnan 2Jithin Krishnan 2
Hi Kogila,
For loop has the below syntax:
For(DataType variable: Collection){

}
So for your requirement the code should be something like this:
public class Myhelloworld
{
    public static void applyDiscount(List<Book__c> books)
    {
        for(Book__c b: Books){
                     b.Price__c *=0.9;
        }
 }

Here 'list<Book__c>' is the datatype of 'Books' , which has a collection (in this case list) of Book__c objects. And inside the loop, variable 'b' gives you 'Book__c' objects in 'Books' one by one. So, the loop does the below line:
b.Price__c *=0.9;
for each of the 'Book__c' inside 'Books'

Hope this helped.
Thanks!

All Answers

pconpcon
This is because you are iterating over a List inside your for loop.  Your code should be
 
public class Myhelloworld {
    public static void applyDiscount(List<Book__c> books) {
        for(Book__c b : books) {
            b.Price__c *=0.9;
        }
    }
}

Additionally, I prefer to use the List<> notation instead of [] because I find it fits better with the Object Oriented nature of Apex
 
Jithin Krishnan 2Jithin Krishnan 2
Hi Kogila,
For loop has the below syntax:
For(DataType variable: Collection){

}
So for your requirement the code should be something like this:
public class Myhelloworld
{
    public static void applyDiscount(List<Book__c> books)
    {
        for(Book__c b: Books){
                     b.Price__c *=0.9;
        }
 }

Here 'list<Book__c>' is the datatype of 'Books' , which has a collection (in this case list) of Book__c objects. And inside the loop, variable 'b' gives you 'Book__c' objects in 'Books' one by one. So, the loop does the below line:
b.Price__c *=0.9;
for each of the 'Book__c' inside 'Books'

Hope this helped.
Thanks!
This was selected as the best answer
Jithin Krishnan 2Jithin Krishnan 2
Oops. I missed a '}' in the code. Corrected code is below:
public class Myhelloworld
{
    public static void applyDiscount(List<Book__c> books)
    {
        for(Book__c b: Books){
                     b.Price__c *=0.9;
        }
   }
}
Kogila KenneyKogila Kenney
Thanks for all your answers