在Scala的类构造函数中引用抽象类型成员

在Scala的类构造函数中引用抽象类型成员,scala,type-members,Scala,Type Members,我可以有一个字段引用Scala中的抽象类型成员,例如 abstract class C { type T val t: T } 但对于构造函数参数,我似乎不能做同样的事情: abstract class C(t: T) { // not found: type T type T } class C[A](c: A) { type T = A } 为什么?类的第一行定义是构造函数,因此它独立于类的给定实现(因为您正在构建它,所以还不能知道抽象类型成员) 但是,您可以为类指定一

我可以有一个字段引用Scala中的抽象类型成员,例如

abstract class C {
  type T
  val t: T
}
但对于构造函数参数,我似乎不能做同样的事情:

abstract class C(t: T) { // not found: type T
  type T
}
class C[A](c: A) {
  type T = A
}

为什么?

类的第一行定义是构造函数,因此它独立于类的给定实现(因为您正在构建它,所以还不能知道抽象类型成员)

但是,您可以为类指定一个类型参数:

abstract class C[T](c: T) {
}
这样就可以在构造函数中使用
T
(现在它只是一个依赖于类型的方法)。请注意,类型参数和成员是两件不同的事情,因此您不能这样做:

val stringC = new C("foo") {}  // the {} enables instantiation of abstract classes
val other: stringC.T = "bar"
如果要使用
stringC.T
表示法,则需要定义与类型参数相等的类型成员:

abstract class C(t: T) { // not found: type T
  type T
}
class C[A](c: A) {
  type T = A
}

不能这样做的主要原因是如何在scala中实现多态性。您的问题的答案将涵盖相当多的领域,这将需要一些时间来解释。尝试阅读下一篇文章:如果需要更深入的理解,可以深入研究类型参数和隐式参数。