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.
[Note: I am not recommending that you do this.] There's a fair chance you can accomplish what you want. The cast to this.type is a lie, but the JVM doesn't know that and can't throw an exception because the singleton type is a scala concept.
Now if you're actually using the singleton property of this.type anywhere, this will get you in trouble in a hurry. But if all you want to do is get covariant return types without all the trouble of typing them, with only the small downside of the huge ugly cast all over the place:
And in action:
this.type is the unique type of this particular instance. It's a singleton type - a distinct type from any other instance of the same class. This works
But this does not
this.type isn't needed that often, but it can be used to express some constraints that can't be expressed otherwise
For instance, here the Inner class says each instance's outer method will return the specific Outer instance from which it came.
This article has another nice example of using this.type to enable method chaining across subclass boundaries: http://scalada.blogspot.com/2008/02/thistype-for-chaining-method-calls.html