adapt<E> method

Set<E> adapt<E>([
  1. Object? source
])

Converts the given source or this into a strongly-typed Set<E>.

Example:

final adaptable = AdaptableSet();
adaptable.addAll([1, 2, 3]);
final typedSet = adaptable.adapt<int>(); // Set<int>

Implementation

Set<E> adapt<E>([Object? source]) {
  source ??= this;

  if (source is HashSet) {
    final set = HashSet<E>();
    for (var e in source) {
      set.add(e as E);
    }

    return set;
  }

  if (source is collection.HashSet) {
    final set = collection.HashSet<E>();
    for (var e in source) {
      set.add(e as E);
    }

    return set;
  }

  if (source is Set) {
    return Set<E>.from(source);
  }

  throw IllegalArgumentException('Cannot adapt $source to Set<$E>');
}