24

My question is pretty much in the title. I would like to create an interface and then initialize it with a definition of the methods right then and there. Anyone familiar with Java would recognize this style of code.

If anyone wants use case, A Filter interface with a method filterOut. Another class has a method that takes a list of sobjects and an object of type Filter and returns only the items that match the conditions layed out in that Filter's filterOut method. Rather than create a pile of named inner or outter classes, it woubl be nice to just go:

filterList(listOfObjects, new Filter{
    Boolean filterOut(SObject obj){
        return obj.name == 'Bob';
    }
}

Can anyone tell me if this is possible?

2 Answers 2

14

Afraid it's not supported. Apex does have inner classes, up to one level deep, but there is no support for anonymous inner classes.

The closest you're going to be able to do is make private inner classes and use those in methods, which half defeats the point.

2
  • I figured, the documentation said nothing of the sort but I thought to ask anyway. Thanks. Mar 29, 2014 at 14:23
  • Oddly, it appears inner classes used to work in anonymous Apex - ref: Is anyone using classes in anonymous apex?. With Spring 15 I just get a GACK 202766208-43981 (-1286861626) Apr 30, 2015 at 22:28
2

Good thing @ca_peterson is pushing this as he joint forces with Salesforce. Have a look a this Dreamforce '19 Talk at around 15:45 and also mentioned in the Q&A part. I guess this feature will be announced soon.

2
  • What about generics and lambdas? Oct 4, 2019 at 12:45
  • @christian-menzinger I admire your optimism ;-) We're 2,5 years later now and no sign of anonymous inner classes. Or any other fixes/improvements in Apex, I might add. Sadly, it doesn't seem to be a priority at Salesforce...
    – Frans
    Feb 5 at 17:53

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.