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")
}
Since this is Scala 2 you have two options.
1. Vanilla Scala
Using only vanilla Scala, you can do this:
This may work if you never want to abstract over
A, but if you do then usingProductis extremely unpleasant.2. Shapeless
If you use Shapeless which means you may use
HListinstead ofProduct, 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.