I am currently at a bit of trouble finding a way to write this generic Set method.
Due to the fact that Apex does not have a Set operation called containsAny
, I decided to write my own version within my umbrella/catch all Utility class for future projects down the line. Unfortunately, I came across some issues developing it.
The code below:
public static Boolean SetContainsAny(Set<Object> currentSet, Set<Object> comparingSet)
{
for(Object setElement : comparingSet)
if(currentSet.contains(setElement))
return true;
return false;
}
With this example (Example A):
Set<String> stringSet = new Set<String>{ '1', '6' };
Set<Integer> integerSet = new Set<Integer>{1, 2, 3};
Boolean containsAny = GeneralUtilities.SetContainsAny(stringSet, integerSet);
Please note: I used two different types of Sets to show-case it should take any set. I planned on checking if they both matched the same instance later.
Gave me the following error:
Method does not exist or incorrect signature: GeneralUtilities.SetContainsAny(Set, Set)
So I figured I could modify the example to get around it:
Set<String> stringSet = new Set<String>{ '1', '6' };
Set<Integer> integerSet = new Set<Integer>{1, 2, 3};
Boolean containsAny = GeneralUtilities.SetContainsAny((Set<Object>)stringSet, (Set<Object>)integerSet);
This however, gave me the following error:
Incompatible types since an instance of Set is never an instance of Set
So I decided, I could get around it by changing the signature:
public static Boolean SetContainsAny(Object currentSet, Object comparingSet)
{
for(Object setElement : (Set<Object>)comparingSet)
if(((Set<Object>)currentSet).contains(setElement))
return true;
return false;
}
This saved to the server, but when I tried running my first example (Example A), I got the following error:
System.TypeException: Invalid conversion from runtime type Set to Set
Now aside from doing the obvious to my example:
Set<Object> stringSet = new Set<String>{ '1', '6' };
Set<Object> integerSet = new Set<Integer>{1, 2, 3};
Is there anyway to make the Utility method perform correctly?