public static <V extends Val> Comparator<Val> asGenericComparator(final Class<V> type,
                                                                      final Comparator<Val> comparator,
                                                                      final Comparator<Val> genericComparator) {

        // If this comparator is called from ValComparators.GENERIC_COMPARATOR then it means
        // we do the isInstance check in there and in here, but it gives some protection
        // if this comparator is called directly for a Val type that is not appropriate
        // for the delegate comparator.
        return (val1, val2) -> {
            if (type.isInstance(val1) && type.isInstance(val2)) {
                // Both non-null and same type so use type's own comparator
                return comparator.compare(val1, val2);
            } else {
                // Fall back to our generic one to deal with mixed types
                return GENERIC_CASE_SENSITIVE_COMPARATOR.compare(val1, val2);
            }
        };
    }
@param comparator A comparator that will only be comparing non-null {@link Val} instances
                  of the same type.
@return A generic comparator for {@link Val} instances that will defer to a type specific
comparator if the values being compared are both match type, if not it will use a generic
comparator.
stroom-query/stroom-query-language/src/main/java/stroom/query/language/functions/ValComparators.java