I have a few objects that have the same fields (referring to Article Types) such as: FAQ__kav, Tutorial__kav, Video__Kav

Is it possible to add all of these records to a single list (I guess of type Sobject) and then iterate over it? If so, what's the correct syntax?

Hoping to find something like this:

Faq__kav record1;
Tutorial__kav record2;
Video__kav record 3;

List<Sobject> kbList = new List<Sobject>();


for(Sobject record : kbList){
  if(Sobject is type of FAQ__kav)
     do something...
  else if (Sobject is type of Tutorial__kav)
     do something else

1 Answer 1


You can use this dynamic access technique (all SObjects support map-like methods):

for (Sobject record : kbList) {
    String stringField = (String) record.get('StringFieldApiName');

to avoid the type-specific if/elseif/else coding for the common fields.

If you do need type-specific logic, the relatively new switch is a good way to do that:

for (Sobject record : kbList) {
    switch on record {
        when Faq__kav f {
            // f is a reference of type Faq__kav in this block
        when Tutorial__kav t {
            // t is a reference of type Tutorial__kav in this block
        when Video__kav v {
            // v is a reference of type Video__kav in this block
  • I didn't know that switch is available in Apex, thanks @Keith C!
    – Json
    Commented Oct 21, 2018 at 13:39
  • 1
    @Json Yeah it's fairly new so you don't see many examples of it. Not sure if the class API version needs to be set to the latest or not - best to do that anyway if it is new code.
    – Keith C
    Commented Oct 21, 2018 at 13:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .