Reputation: 651
I am trying to specify a return type of tuple within a tuple:
class First {
def tupleReturnType(): (Any, Int) = {
val tup = (1, 2, 3) // This can be variable in length
val i = 4
(tup, i)
}
}
and call it for example:
"First Test" must "understand tuple type" in {
val first = new First()
val (tup, i) = first.tupleReturnType()
assert(tup == (1, 2, 3))
assert(i == 4)
}
I can get this to compile using Any
type but I would prefer something specific. Any suggestions? I've researched but not found this specific question elsewhere.
I tried ()
as a type but got a compile failure.
Upvotes: 3
Views: 658
Reputation: 9698
I believe this is changing in Scala 3 / Dotty, but for now, tuples are instances of TupleN
class, with N = 1, 2, 3, ..., 22
. So in order to achieve what you want, you would need some kind of parent type which encapsulates all tuple types.
Here's what Tuple3
looks like:
final case class Tuple3[+T1, +T2, +T3](val _1 : T1, val _2 : T2, val _3 : T3) extends scala.AnyRef with scala.Product3[T1, T2, T3] with scala.Product with scala.Serializable {
override def toString() : java.lang.String = { /* compiled code */ }
}
Here we can see that the closest common supertype of TupleN instances is scala.Product
, so you could say:
def tupleReturnType(): (Product, Int)
Upvotes: 6