Having a language feature that works in some cases but not in
other cases depending on whether the compiler can see the
constructor or not is not a good design.
Arne
Nonsense. The compiler does not need to see the constructor or the
method definition. The method could just as well be in an interface (a
trait in Scala terminology).
The type "this.type" is a singleton type that is unique for each object.
It is simply an explicit construct that says the return value of a
method in a class or interface X is the object itself. Among other
things that means that if it is called on a reference of type Y (where Y
is a subtype of X) the return type is Y and not X.
The construct can be used to achieve what the OP intended. It has a more
important function in Scala though. Scala has path dependent types where
not only the type but also the actual identity returned by a method can
be significant. With path dependent types you sometimes need to narrow
the return type of a method in class X to this.type instead of X to
express that no other instance of X will be returned.
Nothing weird going on here and not very much different from covariant
return in Java where the type of the reference matters as well.
Silvio
For those interested, a tiny example:
class X
{
class Y
def me : X = this
def myself : this.type = this
def createY = new Y
var y : Y = _
}
val x1 = new X
val x2 = new X
x1.y = x1.myself.createY //fine
x2.y = x2.me.createY //type mismatch, expected x2.Y found X#Y
x1.y = x2.y //type mismatch, expected x1.Y found x2.Y
x2.y = x1.createY //type mismatch, expected x2.Y found x1.Y
Here x1.Y is type Y from X instance x1 while X#Y is the less restricted
type of all Ys from any X.