给出以下Scala定义
abstract class C {
type T1 <: { def m() : Int }
type T2 <: { def n() : Int }
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在C中定义第三种类型,它被限制为T1和T2的子类型?例如
type T3 <: T1 & T2 // does not compile
Run Code Online (Sandbox Code Playgroud)
在我看来,这部分不起作用的部分原因是我不能确定这不会导致非法约束(例如从两个类继承).因此,一个相关的问题是,如果我可以约束T1和T2,这将是合法的,例如要求它们都是特征.
Ben*_*mes 11
这样做你需要的吗?
type T3 <: T1 with T2
Run Code Online (Sandbox Code Playgroud)
这并不需要T1和T2两者都是特征 - 例如,您可以使用一个特征和一个类来创建有效的实现(哪个是哪个都无关紧要).
如果你试图定义Cwhere T1和哪个T2类的具体子类型然后它不会编译,所以我不担心在约束中强制执行此操作.
当然可以,但是类型交集是用,而不是&.
abstract class C {
type T1 <: { def m() : Int }
type T2 <: { def n() : Int }
type T3 <: T1 with T2
}
class X extends C {
trait T1 {def m(): Int}
class T2 {def n(): Int = 3}
class T3 extends T2 with T1 {def m(): Int = 5}
}
Run Code Online (Sandbox Code Playgroud)
如果T1和T2恰好都是类,那么你将无法进行具体的实现