I'd like to be able to use this.type to define a method that makes new instances of an immutable case class. Something like this:
trait Expression
{
def left : Expression
def right : Expression
def new_with_changes(l : Expression, r : Expression) : this.type
}
case class Derived(left : Expression, right : Expression)
{
def new_with_changes(l : Expression, r : Expression) : this.type =
{
new Derived(left, right)
}
}
Unfortunately, the compiler complains
test.scala:13: error: type mismatch;
found : Derived
required: Derived.this.type
new Derived(left, right)
^
one error found
How come the new case class doesn't match this.type?
If I change this.type to Base in Base.new_with_changes and Derived in Derived.new_with_changes that works, but it seems it's missing out on the nicety of this.type.
Edit: The real intent of the question is why not have an equivalent way in Scala to declare that the caller of the down perform the downcast, much in the same way that this.type does, but for general types. I don't think it would be easy, but it would be nice.