![]() When you have a Fruit and want to use it as an Apple it usually means you obtained the Fruit through some means that generally could return any kind of Fruit, but in this case you know it was an Apple. If you want to create an Apple and use it as an Apple, you store it in an Apple variable, not a Fruit one. Since the information was only thrown away "locally", sure, the compiler could maintain the knowledge that parent is really an Apple, even though its declared type is Fruit.īut usually nobody does that. Then you want to use the same refernce as an Apple again. In situations like your example, the object was created as an Apple and then that knowledge was thrown away by storing the refernce in a variable of type Fruit. Usually downcasting is what you do when the statically known knowledge the compiler has about the type of something is less specific than what you know (or at least hope). However, in general the problem is undecidable, so we can't expect the compiler to perform too much magic. 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. Many widespread languages, though, chose the simpler and more pragmatic approach of simply returning T and raising an error otherwise. One could argue that a properly designed programming language would forbid downcasts completely, or provide safe casts alternatives, e.g. ![]() 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). Essentially, the programmer is telling the compiler "trust me, I know better - this will be OK at runtime". Since the second is a dangerous operation, most typed programming languages require the programmer to explicitly ask for it. Downcasts can result in a runtime error, when the object runtime type is not a subtype of the type used in the cast. ![]()
0 Comments
Leave a Reply. |