In Scala, define a generic tuple type with variable length and multiple types

315 views Asked by At

How can I define a generic tuple type that can

  • have variable length
  • contain different types

?

In the below example, I would need to define the return type of foo in trait A to match the implementations of the children objects.

trait A {
  def foo: // how to define the return type here?
}

object O1 extends A {
  def foo: (Int, String) = (123, "a string")
}

object O2 extends A {
  def foo: ((String, Boolean), Int) = (("string inside a sub-tuple", true), 0, "another string")
}
1

There are 1 answers

1
Luis Miguel Mejía Suárez On

Since this is Scala 2 you have two options.

1. Vanilla Scala

Using only vanilla Scala, you can do this:

trait A {
  type O <: Product
  def foo: O
}

object O1 extends A {
  override final type O = (Int, String)

  override def foo: (Int, String) =
    (123, "a string")
}

This may work if you never want to abstract over A, but if you do then using Product is extremely unpleasant.

2. Shapeless

If you use Shapeless which means you may use HList instead of Product, that would make harder the use of a concrete implementation but easier an abstract usage (but still pretty unpleasant).


Anyways, I still recommend you to check if this is really the best solution to your meta-problem.