Why is Scala's syntax for tuples so unusual?

Viewed 29937

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?

8 Answers

Starting Scala 3 tuples can be indexed in type-safe manner using apply method which is implemented with facilities such as match types, literal-based singleton types, and dependent functions types

/** Get the i-th element of this tuple.
 *  Equivalent to productElement but with a precise return type.
 */
inline def apply[This >: this.type <: NonEmptyTuple](n: Int): Elem[This, n.type] =
  runtime.Tuples.apply(this, n).asInstanceOf[Elem[This, n.type]]

giving

val t = (42, 3.14, "woohoo")
// t: Tuple3[Int, Double, String] = (42,3.14,woohoo)
t(0)
// res0: Int = 42
t(1)
// res1: Double = 3.14
t(2)
// res2: String = woohoo

Note the precise type which changes according to type of element at particular index. Also out of bounds index t(3) results in compile-time error

t(3)
  ^
  index out of bounds: 3
Related