Suppose 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) }
Then I try to add another attribute as mixin, for which I want the return type for the copy to be the appropriate type (this means that the call copy on mixin returns the mixin type, setting B to the appropriate type), I was unable to get this to compile or even understand where the override keyword should run.
Edited: I clarified 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 a suitable type B and copy method for DecBase, so that the copy returns DecBase, and also, why does not this compile?
println(((new MyBase("ofer") with DecBase)).rep)
This is what I would achieve in Java (with some muck using recursive generic types). I'm sure you can 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
scala
user44242
source share