World's most popular travel blog for travel bloggers.

[Solved]: Automatic Downcasting by Inferring the Type

, , No Comments
Problem Detail: 

In java, you must explicitly cast in order to downcast a variable

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 required  
Asked By : Sam Washburn

Answered By : chi

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 Option<T>. 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.

Best Answer from StackOverflow

Question Source : http://cs.stackexchange.com/questions/64732

0 comments:

Post a Comment

Let us know your responses and feedback