Search code examples
scalascala-3hlistdottysingleton-type

How Assigning TupleN value to *: type variable works in Scala 3?


From the type hierarchy tree in scala

  • let a:Tuple2[Int,Int], I know Tuple2[Int,Int] extends from Product2[Int,Int];
  • let b:1 *: 2 *: EmptyTuple has type Tuple (refined as Int *: Int *: EmptyTuple)

They are different types and don't have any parent relation. The only thing they both have is Product, they both extend from Product.

But I can assign a to b and opposite, why?


Solution

  • In Scala 3, the Tuple1...Tuple22 types are synthetically modified by the compiler to extend the *: types. That is, Tuple2[A, B] is modified to extend A *: B *: EmptyTuple (which extends Tuple).

    Therefore, you can assign a Tuple2[Int, Int] to a Int *: Int *: EmptyTuple. Likewise, the reverse is possible because a A *: ... EmptyTuple will be treated like a TupleN whenever it can (<= 22 type arguments).