Both can store mixed types but a Set seems far more powerful since it features union, intersection or diff among other.
Another important difference is that tuples aren't considered collections.
I'm learning Scala and I'm wondering why would I want to use tuples over sets.
The main advantage of tuples is that type information is maintained. This is a big deal in a statically typed language like Scala.
scala> (4.2,'c',true,"blah",7)
res2: (Double, Char, Boolean, String, Int) = (4.2,c,true,blah,7)
scala> Set(4.2,'c',true,"blah",7)
<console>:11: warning: a type was inferred to be `Any`; this may indicate a programming error.
Set(4.2,'c',true,"blah",7)
^
res3: scala.collection.immutable.Set[Any] = Set(true, blah, 7, c, 4.2)
Once our Set
type is Set[Any]
then we've lost type information that could be valuable in avoiding problems (i.e. bugs) down the line.
Also, pulling elements from a Set[Any]
can be a pain. Every element extracted from it [e.g. mySet.head
] will probably have to be tested for type before it can be used. Getting individual elements from a tuple can also be rather cumbersome [myTup._3
] but the compiler, and the rest of your code, knows exactly what it's getting.
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