Idea: Lazy upcasting
Mitja Slenc
mslenc at gmail.com
Tue Mar 27 07:54:25 PDT 2007
Aarti_pl wrote:
> Proposition has also nothing to do with implicit downcasting. It has
> more with upcasting, but in opposite way - implicit upcasting should be
> disallowed in some cases :-)
>
> If my proposition is not clear in some aspects, feel free to ask
> questions. I am not a native speaker, so parts of this proposition could
> be unclear...
OK, let me try to restate the problem, to see if I get it - some methods
always return this, so that several invocations on the same object can
be chained together : foo.a().b().c(). But, if one defines an inherited
class and doesn't override those methods to indicate the new return
type, calling base class' methods results in losing information about
the derived type, so neither can the object be assigned to references of
the derived type, nor can new methods of the derived class be called
after calling base methods.
The problem with your suggestion of 'lazy upcasting' is that it's quite
impossible for the compiler to verify whether all the methods in fact
return this (for example, the source file could've been compiled
previously and its source is no longer available), so it can't tell
whether to do the usual thing (use the declared return type) or not (use
the derived type).
A better idea would be to use a special keyword for the return type to
indicate what is going on:
class Base
{
return_this foo(int i) { ... }
}
class Derived : Base
{
return_this bar(int i) { ... }
}
void main()
{
Derived d = (new Derived).foo(1).bar(2); // currently an error
}
Another idea would be to treat void methods as if they implicitly
returned this, though I'm quite sure there are hidden dangers in doing
so. But, method definitions could certainly be cleaner and more obvious
(it's not always clear whether the object returned is supposed to be a
new one, or the called one), and I guess relatively many temporary
variables serve only the purpose of being able to call more than one
method on a given object (without fetching it twice from somewhere), and
those would often no longer be needed, as well.
xs0
More information about the Digitalmars-d
mailing list