Why is Scala's syntax for tuples so unusual?

yura picture yura · Jul 30, 2011 · Viewed 27.7k times · Source

In mathematics and computer science, a tuple is an ordered list of elements. In set theory, an (ordered) n-tuple is a sequence (or ordered list) of n elements, where n is a positive integer.

So, for example, in Python the 2nd item of a tuple would be accessed via t[1].

In Scala, access is only possible via strange names t._2.

So the question is, why can't I access data in tuples as Sequence or List if it is by definition? Is there some sort of idea or just yet not inspected?

Answer

Jean-Philippe Pellet picture Jean-Philippe Pellet · Jul 30, 2011

Scala knows the arity of the tuples and is thus able to provide accessors like _1, _2, etc., and produce a compile-time error if you select _3 on a pair, for instance. Moreover, the type of those fields is exactly what the type used as parameter for Tuple (e.g. _3 on a Tuple3[Int, Double, Float] will return a Float).

If you want to access the nth element, you can write tuple.productElement(n), but the return type of this can only be Any, so you lose the type information.