上下文子类型的类型参数

type parameters for context subtype

对于 类 和方法,我已经多次遇到这个构造,但我不明白你为什么要使用:

class MyClass[C <: Context](ctx: C)

而不是:

class MyClass(ctx: Context)

是为了绕过协方差还是什么?

另一个问题如下:

abstract class YYTransformer[C <: Context, T](c: C, t: T) {
     type Ctx = C
}

为什么不简单地使用:

type Ctx = c.type

谢谢

问题 1

它们基本相同,除了以下事实:

class MyClass[C <: Context](ctx: C)

您跟踪 ctx 变量的 class。 这样,就可以做类似的事情:

class MyClass[C <: Context](ctx: C) {
  val m: List[C]
}

这是不可能的:

class MyClass(ctx: Context) {
  val m : List[???]
}

问题 2

正如之前 Seth Tisue 所述,.type 不是 return 您正在调用 .type 的对象的类型,而是单例类型,即是 "suits" 只有这样的对象的类型。