Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why to use Tuple over Set in Scala?

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.

like image 918
Alejandro García Seco Avatar asked Mar 30 '16 20:03

Alejandro García Seco


1 Answers

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.

like image 109
jwvh Avatar answered Sep 28 '22 03:09

jwvh