Tuesday, November 08, 2005

Forced typecasts

The design of the typecasting operators for Freya has been troublesome:
  • Delphi uses the as operator as a "forced typecast": it checks first whether the conversion is possible, and when it's not, it throws an exception.
  • The other typecast operation is an unchecked conversion (actually, it's a compile time cast): just do what I say, even when it's plainly wrong. Syntactically, you must use the type name as a monoparametric function.
  • There's no "atomic" tentative typecast in Delphi. To simulate it, test the source type using the is operator, and if the answer is affirmative, proceed with the compile time typecast.
On the contrary, this is what happens in C#:
  • Tentative casting is implemented by the as operator.
  • The widely known compile-time typecast inherited from C, is now the "forced" typecast operator.
  • There's also an is operator in C#, but there is no compile-time, unchecked typecast.
I felt inclined from the first time to use as as in C#, but I was worried about the confusion this could cause in a Delphi programmer. And then, how should I implement the functional style typecast?
Our final design resembles the design decisions in C#:
  • Tentative casting in Freya is implemented by the as operator.
  • The functional style typecast means a forced typecast in Freya: if the conversion is not possible, it throws an exception.
  • Of course, we keep the meaning of the is operator.
Let's see some code:
o: Object;
b: Button;
o := new Label;
// A tentative typecast.
// A nil reference is stored.

b := o as Button;
// A forced typecast.
// An exception is raised.

b := Button(o);
Of course, I'm writing this after implementing the support for this operations in the Freya compiler.