How to extend an apex set class?

275    Asked by darsh_6738 in Salesforce , Asked on May 5, 2023

 Is there any way I can extend the Set class? I have numerous places in code where if a set has no items, I want to add all the items in another set, but if it does have items, I want to retain only the items in the other set.


This seemed like a good use case for extending the Set class, but Apex complains about the lack of < following>


public with sharing class CoreSet extends Set {
    public Boolean retainAllIfPopulated(Set other) {
        return this.size() > 0 ? this.retainAll(other)
                               : this.addAll(other);
    }
}

Is it possible to extend the built-in Set class?

Answered by Clare Matthews

No, it is not possible to extend an apex set class if it is not abstract or virtual. Unlike in Java in Apex all classes are final by default. But you can use "composition (over inheritance)" and write something like this:


public with sharing class SomeClass {
    private Set objs;
    public SomeClass(Set objs) {
        this.objs = objs;
    }
    public Boolean retainAllIfPopulated(Set other) {
        return objs.size() > 0 ? objs.retainAll(other)
                               : objs.addAll(other);
    }
}

Your Answer

Interviews

Parent Categories