在scala语言中使用type参数创建子类

时间:2015-02-11 19:20:37

标签: scala inheritance type-parameter

所有!

我想使用type参数创建子类,但scala给出了"error: class type required but T found"。例如:

abstract class Base {def name:String}
class Derived extends Base {def name:String = "Derived"}
class Main[T <: Base] 
{
    class SubBase extends T {}; // <--- error: class type required but T found
    val x:SubBase; 
    println(x.name) 
}
val m:Main[Derived]

我想要这种方式而不是正常继承,因为在实际代码中我有惰性变量,在Base中声明并在Derived中定义,并且这些变量应该在Main class <中执行计算/ p>

我怎么做?提前致谢

1 个答案:

答案 0 :(得分:1)

您可以使用自我类型来实现类似的效果:

abstract class Base {def name:String}
class Derived extends Base {def name:String = "Derived"}
class Main[T <: Base] 
{
    trait SubBase { this: T => };
    val x:SubBase; 
    println(x.name)  // <--- error: value name is not a member of x
}
val m:Main[Derived]

但是,这只会让您访问班级中T的成员。因此,您还可以SubBase扩展Base

abstract class Base {def name:String}
class Derived extends Base {def name:String = "Derived"}
class Main[T <: Base] 
{
    trait SubBase extends Base { this: T => }
    val x:SubBase; 
    println(x.name)
}
val m:Main[Derived]

这将编译,但没有用,因为SubBase也是T的事实对SubBase仍然是私有的。