Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart Set.from() vs Set.of()

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}
like image 289
Md. Shahedul Islam Shahed Avatar asked Sep 14 '19 14:09

Md. Shahedul Islam Shahed


2 Answers

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.

like image 118
Spatz Avatar answered Sep 21 '22 23:09

Spatz


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).

like image 24
Tom Yeh Avatar answered Sep 23 '22 23:09

Tom Yeh