Oxygene - how to "strong type"?


(mcabak) #1

How should I do “type safe” programming in Oxygene in the following (uncompilable) example:

type
  Degrees = Single;
  Rads = Single;

  method Rotate (anAngle: Degrees);
  method Rotate (anAngle: Rads);

The Degrees and Rads are only type aliases and are implicitly convertible amongst each other and the base type. The only way I am able to declare these functions in type-safe manner (or at all) is to have Degrees and Rads as classes, but thats an overkill in this case.
I would like NOT to be able to supply wrong type to the method and have no warning - it should not compile.
Did I miss a language feature here, or how do you guys do this?


(marc hoffman) #2
type
  Degrees = type Single;
  Rads = type Single;

should work, I believe.


(mcabak) #3

Yes! I am continuously amazed what Oxygene is capable of, and all the things you incorporated into it.

If it helps anyone, it works, and the necessary operators than can be defined via extension classes.

type
  Degrees = type Single;
  Rads = type Single;

  Degrees_Helpers = public extension class (Degrees)
    operator Add (left, right: Degrees): Degrees;
  end;

What I failed to achieve is an implicit conversion from Degrees to String, if you can help … ?

Try 1 - fails on “Implicit/explicit operator must have it’s own class type as return or parameter type”

Degrees_Helpers = public extension class (Degrees)
  operator Implicit (val: Degrees): String;
end;

Try 2 - fails on “ld: symbol(s) not found for architecture x86_64” - I suspect because Degrees is not a class.
Extension operator XXX syntax is not supported.

extension method Degrees.Implicit (val: Degrees): String;
begin
  result := Single(val).ToString + "°";
end;

(Carlo Kok) #4

If you need operators I would suggest a record with just a single in them. It will let you expose just what you want.