-
Notifications
You must be signed in to change notification settings - Fork 242
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add safer types of casts #565
Comments
FWIW I'm not sure what the spec should say when |
This will work only for simple classes. TBH I don't see a big win over the current way (using |
TBH I'm not feeling strongly myself, but I've definitely found code where people needed an upcast and used |
This could be somewhat useful feature, especially for retrofitting types to a legacy codebase. However, supporting anything beyond simple classes would be hard (see below).
Sometimes the need for a cast is deep within an expression, and using an assert would require somewhat non-trivial refactoring. People will often use a Some discussion of special cases:
One way to work around some of the limitations would be to remove the |
The asymmetry in the original proposal also seems a bit inconsistent to me. I would expect |
To defend the asymmetry: in other languages downcasts always cause a runtime check to be generated, while upcasts don't. Possibly we could have different names. (C++ has |
The only form of cast expression we have is intended to completely bypass the type system. This is like most forms of casting in C (not counting conversions) -- it never fails either at runtime or at compile time.
Maybe we can add two new types of casts:
Downcast
downcast(T, E)
checks at compile time that the type of expressionE
is a supertype ofT
, and checks at runtime thatE
is in fact an instance ofT
. As a special case, if the type ofE
isAny
, the compile time check always succeeds, but the runtime check is still performed.A possible implementation:
It's intentional that this uses
assert
(though debatable): the intended use case is currently handled by inserting the sameassert
manually. IOW:is roughly equivalent to:
Upcast
Probably much less needed, but proposed for symmetry and because occasionally it's useful.
upcast(T, E)
should check at compile time thatT
is a supertype of the type ofE
, and at runtime it's a no-op.A possible implementation:
This fragment:
is roughly equivalent to:
except that it works even if the type of
x
has already been declared.The text was updated successfully, but these errors were encountered: