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;
  • I saw that before, when I changed to == I get the error "Expression cannot be a statement", which seemed more wrong. – Dan Wooding Jan 8 '17 at 19:10
  • Note: Despite having a completely different title, the answer is exactly the same. – sfdcfox Jan 8 '17 at 19:11
  • I'll answer based on the error in your comment, because that's your real problem. – sfdcfox Jan 8 '17 at 19:13
  • I'd appreciate it, should I edit my question to highlight that? – Dan Wooding Jan 8 '17 at 19:14

"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)) { 
            new Revenue_Pipeline__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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.