Casts
A variable of one type can be cast down to a more-specific target type by using a cast function. The name of the cast function is the name of the target type, followed by ?
. The cast function returns an optional of the target type, with a value if the cast was successful, or no value if the cast was unsuccessful.
For A < B
, with a:A
, b:B
, and c:A?
:
b <- a; // OK, as A < B
c <- A?(b); // OK, but A < B so must use cast
c
may be used to check whether the cast succeeded, and if so, to retrieve the result:
if c? {
f(c!); // cast was successful, can do something with c
}
b:B?
instead of b:B
, the above example is the same.