所有!
我想使用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>
我怎么做?提前致谢
答案 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
仍然是私有的。