[英]Scala how to specify a return type of tuple in a tuple
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
类型进行编译,但我更喜欢特定的东西。 Any suggestions? 有什么建议? I've researched but not found this specific question elsewhere.
我研究过但没有在其他地方找到这个具体问题。
I tried ()
as a type but got a compile failure. 我尝试
()
作为一种类型,但编译失败。
I believe this is changing in Scala 3 / Dotty, but for now, tuples are instances of TupleN
class, with N = 1, 2, 3, ..., 22
. 我相信这在Scala 3 / Dotty中有所改变,但是现在,元组是
TupleN
类的实例,其中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: 这是
Tuple3
样子:
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: 在这里我们可以看到最接近的TupleN实例的常见超类型是
scala.Product
,所以你可以说:
def tupleReturnType(): (Product, Int)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.