[英]How to say that a type parameter must have one supertype of alternative supertypes?
One can say a type parameter T must have a specific supertype S_1: 可以说类型参数T必须具有特定的超类型S_1:
class Test[T <: S_1]
Is there a way to say, that a type parameter must have at least one supertype of multiple supertype alternatives ? 有没有办法说,一个类型参数必须至少有一个超类型的多个超类型备选方案? Something like (pseudocode) :
像(伪代码)的东西:
class Test[T <: S_1 || S_2]
Or: Is this not possible, because such a construction makes no sense and would be a hint of a design mistake in the code ? 或者:这是不可能的,因为这样的结构毫无意义,并且会在代码中暗示设计错误?
Short answer: The intuitive solution is to make S_1
and S_2
share a common trait that represents the set of abilities you require for your type parameter T
. 简答:直观的解决方案是让
S_1
和S_2
共享一个共同的特征,代表你的类型参数T
所需的一组能力。 Use that trait as the upper bound for T
. 使用该特征作为
T
的上限。
More possibilities: 更多可能性:
If S_1
and S_2
are unrelated in nature and your requirement for the type T
is that it has certain members (that both S_1
and S_2
happen to implement), you can use a structural type to formulate that (the concept behind is called duck typing ). 如果
S_1
和S_2
本质上是无关的,并且您对类型T
要求是它具有某些成员( S_1
和S_2
恰好实现),您可以使用结构类型来表示(后面的概念称为duck typing ) 。
If for some reason you really require T
to be a subclass of S_1
or S_2
, and you can't change those types, you can use implicits to convert both of these to a newly introduced internal type S_1_or_2
, which you can then use as an upper bound for your T
. 如果由于某种原因你真的要求
T
成为S_1
或S_2
的子类,并且你不能改变这些类型,你可以使用implicits将这两种类型转换为新引入的内部类型S_1_or_2
,然后你可以将其用作T
上限。
Let me expand on Niklas second alternative. 让我扩展Niklas的第二种选择。 Implicit parameters can be used to prove something about the type, so this seems like just the thing.
隐式参数可以用来证明关于类型的东西 ,所以这看起来就像是事情。 It would go like this:
它会是这样的:
class ThingIWantToProve[T]
object ThingIWantToProve {
// Here I define the proofs I need
implicit def s1IsProvable: ThingIWantToProve[S_1] = new ThingIWantToProve[S_1]
implicit def s2IsProvable: ThingIWantToProve[S_2] = new ThingIWantToProve[S_2]
}
class Test[T : ThingIWantToProve] // here I use a context bound
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.