Is there any way I can extend the Set class? I have numerous places in code where if I 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 the extending of the set and the declaration of a Set argument in the following code:
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?
Set<Object>is tough to use. You wouldn't be able to pass aSet<Account>into theSomeClassconstructor or intoretainAllIfPopulated(). Heck, evenSet<Object> objSet = new Set<Object>(myAccountSet);doesn't work. This is something I ran into several years ago. – Derek F Nov 26 '21 at 20:06Set<?>is broken in Apex, but I didn't focus on this topic answering this specific question. – Oleh Berehovskyi Nov 26 '21 at 20:11