假设我有一个基类:
这是我在Java中可以实现的东西(使用递归泛型类型有些麻烦)。我相信在Scala中可以做得更好。
编辑:
使用
我收到了以下编译器错误。
abstract class Base {
type B<: Base
def rep:String
def copy:B
}
class MyBase(override val rep:String) extends Base {
type B = MyBase
override def copy = new MyBase(rep)
}
然后我试图添加另一个trait作为mixin,我希望copy的返回类型是适当的类型(也就是调用mixin上的copy方法返回mixin类型,通过将B设置为适当的类型)。我无法使其编译通过,甚至不知道override关键字应该放在哪里。
已编辑:我已经完善了这个例子。
abstract class Base {
type B <: Base
def rep:String
def copy:B
}
class MyBase(val rep:String) extends Base {
type B = MyBase
def copy = new MyBase(rep)
}
trait DecBase extends Base {
abstract override def rep = "Rep: "+super.rep
}
我的问题是,我该如何为DecBase声明适当的类型B和复制方法,以便复制返回一个DecBase,并且,为什么这个代码无法编译?
println(((new MyBase("ofer") with DecBase)).rep)
这是我在Java中可以实现的东西(使用递归泛型类型有些麻烦)。我相信在Scala中可以做得更好。
编辑:
使用
trait DecBase extends Base {
override type B = DecBase
abstract override val rep= "Dec:"+super.rep
abstract override def copy = new MyBase(rep) with DecBase
}
我收到了以下编译器错误。
error: overriding type B in class MyBase, which equals com.amadesa.scripts.MyBase;
type B in trait DecBase, which equals com.amadesa.scripts.DecBase has incompatible type
println(((new MyBase("ofer") with DecBase)).rep)
error: overriding type B in class MyBase, which equals com.amadesa.scripts.MyBase;
type B in trait DecBase, which equals com.amadesa.scripts.DecBase has incompatible type
abstract override def copy = new MyBase(rep) with DecBase