Scala:抽象类型可以是多个其他类型的子类型吗?
鉴于以下 Scala 定义,
abstract class C {
type T1 <: { def m() : Int }
type T2 <: { def n() : Int }
}
是否有一种方法可以在 C 中定义第三种类型,该类型被限制为 T1 和 T2 的子类型?例如,
type T3 <: T1 & T2 // does not compile
在我看来,这不能按书面方式工作的(部分)原因是我无法确定这不会导致非法约束(例如从两个类继承)。因此,一个相关的问题是我是否可以限制 T1 和 T2 以使这合法,例如要求它们都是特征。
Given the following Scala definitions
abstract class C {
type T1 <: { def m() : Int }
type T2 <: { def n() : Int }
}
is there a way to define a third type within C that is constrained to be a subtype of both T1 and T2? E.g.
type T3 <: T1 & T2 // does not compile
It seems to me that (part of) the reason this won't work as written is that I cannot be sure that this will not lead to an illegal constraint (e.g. inheriting from two classes). Thus, a related question would be if I can constrain T1 and T2 so that this would be legal, e.g. requiring that they both be traits.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这能满足您的需要吗?
这并不要求
T1
和T2
都是特征 - 例如,您可以使用一个特征和一个类来进行有效的实现(无论是哪一个)是哪个)。如果您尝试定义
C
的具体子类型,其中T1
和T2
都是类,那么它将无法编译,所以我不会担心在约束中强制执行此操作。Does this do what you need?
This doesn't require
T1
andT2
to both be traits - you could make a valid implementation using one trait and a class, for example (it doesn't matter which one is which).If you tried to define a concrete subtype of
C
whereT1
andT2
were both classes then it would not compile, so I would not worry about enforcing this in the constraint.当然可以,但是类型交集写作with,而不是&。
如果 T1 和 T2 恰好都是类,那么您将无法进行具体的实现
Sure you can, but type intersection is written with, not &.
if T1 and T2 happens to be both class, you just won't be able to make a concrete implementation