8

In dart, Set class has two different factory constructors Set.from() and Set.of(). Their returned results are same of same type. Is there any use case difference between them ? How to decide which one to use ?

See output of this program:

void main() {
    List<int> myList = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5];

    Set<int> mySetFrom = Set.from(myList);
    Set<int> mySetOf = Set.of(myList);

    print("mySetFrom type: ${mySetFrom.runtimeType}");
    print("mySetFrom: ${mySetFrom}");

    print("mySetOf type: ${mySetOf.runtimeType}");
    print("mySetOf: ${mySetOf}");
}

Output:

mySetFrom type: _CompactLinkedHashSet<int>
mySetFrom: {1, 2, 3, 4, 5}
mySetOf type: _CompactLinkedHashSet<int>
mySetOf: {1, 2, 3, 4, 5}
  • Does this answer your question? [In Dart, what's the difference between List.from and .of, and between Map.from and .of?](https://stackoverflow.com/questions/50320220/in-dart-whats-the-difference-between-list-from-and-of-and-between-map-from-a) – jamesdlin Apr 29 '20 at 05:15

3 Answers3

6

Differences revealed with type inheritance:

Set<Object> superSet = <Object>{'one', 'two', 'three'};

Set.from() constructor can be used to down-cast from superSet

Set<String> subSet = Set<String>.from(superSet); // OK

But Set.of() cannot

Set<String> anotherSubSet = Set<String>.of(superSet); // throws an error
// The argument type 'Set<Object>' can't be assigned to the parameter type 'Iterable<String>'.

I think Set.of() constructor is preferable with exactly the same type because of better performance.

Spatz
  • 18,640
  • 7
  • 62
  • 66
4

There is a good discussion here (it is about List, but applicable to Set too)

Lasse explained it well. In summary, use iterable.toSet() for better performance if the type doesn't change. Use Set.from() for changing type. Don't use Set.of() since it is basically subsumed by the new literal (unless you think of is more readable).

Tom Yeh
  • 1,987
  • 2
  • 15
  • 23
2

Let's look at them:

Set.of:

Set<E>.of(Iterable<E> elements)

Set.from:

Set<E>.from(Iterable elements)

Do you notice a difference?

Set.of takes an Iterable<E> and Set.from takes an Iterable with no explicit type. In other words, Set.of does stronger type-checking of its argument. Set.from is older, and Set.of was added in Dart 2 when strong typing was added. You usually should use Set.of.

https://github.com/dart-lang/sdk/issues/32959 requests that the documentation be improved to clarify this.

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
  • 1
    You should use `Set.of` when you already have an iterable of `E`. You should use `Set.from` when you have some `Iterable` which you happen to know contains only objects of type `E`. – lrn Sep 15 '19 at 20:29