实例化 Scala 类型成员导致错误

Instantiating Scala Type Members results in error

关于为什么我们不能实例化类型成员的快速问题?例如举这个例子:

abstract class SimpleApplicationLoader {
  type MyComponents <: BuiltInComponentsFromContext

  def load(context: Context) = {
    new MyComponents(context).application
  }
}

class SiteServiceApplicationLoader extends SimpleApplicationLoader {
  type MyComponents = SiteApplicationComponents
}

class SiteApplicationComponents(val context: Context) extends BuiltInComponentsFromContext(context) {
      ....
}

SimpleApplicationLoader定义了一个类型参数MyComponents(上限为BuiltinComponentsFromContext)。在load方法中,实例化了类型参数MyComponentsSiteServiceApplicationLoader 将 MyComponents 类型覆盖为 _SiteApplicationComponents)。

无论如何,编译器给出以下错误:

Error:(13, 9) class type required but SimpleApplicationLoader.this.MyComponents found
    new MyComponents(context).application

只是好奇为什么类型成员不能被实例化?有什么解决方法吗?

谢谢!

运算符 new 仅适用于 classes (or "like classes")。类型不是 class,因此 new 不可用。

要实例化任意类型,可以使用函数

def newMyComponents(context: Context): MyComponents

更新(感谢@daniel-werner)

所以摘要 class 看起来像

abstract class SimpleApplicationLoader {
  type MyComponents <: BuiltInComponentsFromContext

  def newMyComponents(context: Context): MyComponents

  def load(context: Context) = {
    newMyComponents(context).application    
  }
}

抽象方法可能在 class 中实现,其中定义了 type

class SiteServiceApplicationLoader extends SimpleApplicationLoader {
  type MyComponents = SiteApplicationComponents
  def newMyComponents(context: Context): MyComponents = 
    new SiteApplicationComponents(context)
}

您不能实例化类型。您只能实例化一个 class.

您的代码中没有任何内容将 MyComponents 限制为 class。它也可以是特征、单例类型、复合类型,甚至是抽象 class,它们也无法实例化。

其他语言有办法将类型限制为 class 类型,或者具有构造函数。例如,在 C♯ 中,您可以将类型约束为 class 或具有零参数构造函数的结构。但是 Scala 没有针对此类约束的功能。