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}
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With