2016-11-16 34 views
0

快速提问为什么我们无法实例化类型成员?例如借此例如:实例化Scala类型成员导致错误

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)。在加载方法中,类型参数MyComponents被实例化。 SiteServiceApplicationLoader将重写MyComponents类型为_SiteApplicationComponents)。

无论如何,编译器提供了以下错误:

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

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

谢谢!

回答

3

运营商new仅适用于classes (or "like classes")。类型不是类,所以new不可用。

实例化一个任意类型,函数可用于

def newMyComponents(context: Context): MyComponents 

更新(感谢@丹尼尔 - 沃纳)

所以抽象类看起来像

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) 
} 
+0

澄清:您建议将一个抽象方法'newMyComponents'(它返回'MyComponents')添加到'SimpleApplicationLoader'。这个方法将在'SiteServiceApplicationLoader'中实现。它是否正确?因为这个含义并没有从第一个代码示例中变得100%清晰。 –

3

你不能实例化一个类型。你只能实例化一个类。

代码中没有什么限制MyComponents成为类。它也可以是一个特征,单例​​类型,复合类型,甚至是抽象类,它们也不能实例化。

其他语言有办法将类型约束为类或具有构造函数。例如,在C中,可以使用零参数构造函数将类型约束为类或结构。但是Scala没有这种约束的特征。

相关问题