Assume I have a base class
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)
}
I then try to add another trait as a mixin, for which I want the return type for copy to be the the appropriate type (meaning that calling copy on the mixin returns a mixin type, by setting B to the appropriate type). I haven't been able to get this to compile, or even to understand where the override keyword should go.
Edited: I have refined the example
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
}
My question is, how do I declare an appropriate type B and copy method for DecBase, so that the copy returns a DecBase , and also, why won't this compile?
println(((new MyBase("ofer") with DecBase)).rep)
This is something I would have achieved in Java (with some nastiness, using recursive generic types). I'm sure that it's possible to do something nicer in Scala.
Edit
Using
trait DecBase extends Base {
override type B = DecBase
abstract override val rep= "Dec:"+super.rep
abstract override def copy = new MyBase(rep) with DecBase
}
I get the following compiler errors
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