[SalesForce] Expression cannot be a statement Error

I want to create a batch job to compare a date and then update a related object. I want to have a short-hand ternary expression as I will have about 60 similar lines depending on the month. I have this code snipit but I get the error:

Expression cannot be a statement

I'm compare if the date field equals my date.newinstance(year,month,day). Why do I get this error?

global void execute(Database.BatchableContext BC, List<Revenue_Pipeline_Schedule__c> revPipeSchedule) {
    List<Revenue_Pipeline__c> revPipe = new List<Revenue_Pipeline__c>();

    for(Revenue_Pipeline_Schedule__c rPS : revPipeSchedule){
        (rPS.Date__c == date.newinstance(2014,10,1)) ? revPipe.add(new Revenue_Pipeline__c(Id=rPS.Revenue_Pipeline__c, Oct2014__c=rPS.Amount__c)) : null;
    }
    update revPipe;
}

Best Answer

"Expression cannot be a statement" is a fairly unique limitation in Apex Code. Unlike most other languages that support ternary operators, you can't use ?: as a shortcut for an arbitrary if statement. While that code would be perfectly acceptable in JavaScript, for example, Apex Code doesn't allow you to have a void return type in a ternary operator. You have to actually write out the if statement:

    if(rPS.Date__c == date.newinstance(2014,10,1)) { 
        revPipe.add(
            new Revenue_Pipeline__c(
                Id=rPS.Revenue_Pipeline__c, 
                Oct2014__c=rPS.Amount__c));
    }

In the general case, you also can't use any other conditional expression without assigning to a variable or using it in a condition statement (while, do, if, etc). For example, none of the following should compile when written as stand-alone expressions.

i == 5;
i < 5;
i > 5;
// etc...
Related Topic