patternMajor
Automatic Downcasting by Inferring the Type
Viewed 0 times
thedowncastinginferringtypeautomatic
Problem
In java, you must explicitly cast in order to downcast a variable
Is there any reason for this requirement, aside from the fact that java doesn't do any type inference?
Are there any "gotchas" with implementing automatic downcasting in a new language?
For instance:
public class Fruit{} // parent class
public class Apple extends Fruit{} // child class
public static void main(String args[]) {
// An implicit upcast
Fruit parent = new Apple();
// An explicit downcast to Apple
Apple child = (Apple)parent;
}Is there any reason for this requirement, aside from the fact that java doesn't do any type inference?
Are there any "gotchas" with implementing automatic downcasting in a new language?
For instance:
Apple child = parent; // no cast requiredSolution
Upcasts always succeed.
Downcasts can result in a runtime error, when the object runtime type is not a subtype of the type used in the cast.
Since the second is a dangerous operation, most typed programming languages require the programmer to explicitly ask for it. Essentially, the programmer is telling the compiler "trust me, I know better -- this will be OK at runtime".
When type systems are concerned, upcasts put the burden of the proof on the compiler (which has to check it statically), downcasts put the burden of the proof on the programmer (which has to think hard about it).
One could argue that a properly designed programming language would forbid downcasts completely, or provide safe casts alternatives, e.g. returning an optional type
In your specific example, the compiler could have been designed to deduce that
Downcasts can result in a runtime error, when the object runtime type is not a subtype of the type used in the cast.
Since the second is a dangerous operation, most typed programming languages require the programmer to explicitly ask for it. Essentially, the programmer is telling the compiler "trust me, I know better -- this will be OK at runtime".
When type systems are concerned, upcasts put the burden of the proof on the compiler (which has to check it statically), downcasts put the burden of the proof on the programmer (which has to think hard about it).
One could argue that a properly designed programming language would forbid downcasts completely, or provide safe casts alternatives, e.g. returning an optional type
Option. Many widespread languages, though, chose the simpler and more pragmatic approach of simply returning T and raising an error otherwise.In your specific example, the compiler could have been designed to deduce that
parent is actually an Apple through a simple static analysis, and allow the implicit cast. However, in general the problem is undecidable, so we can't expect the compiler to perform too much magic.Context
StackExchange Computer Science Q#64732, answer score: 24
Revisions (0)
No revisions yet.