easy type reflection

as a continuation of this post, we'd like to mention how oh-lang improves upon type reflection from most languages. types are written with a prefix #, and the default name for a variable of type #some_type is some_type. this works in reverse, and has two effects.

the first effect: oh-lang tries to look up #another_type if your variable is named another_type, and if the type exists, it will be an error to use any other type for another_type (if specified explicitly). e.g., i32: #str = "asdf" is an automatic compile error because #i32 exists and so i32 should be a 32-bit signed integer. however, x: #dbl = 1.234 is fine (as long as no #x is in scope or if it is a double-precision type).

the second effect: variables can look up their types without reflection helper functions like typeof or instanceof by just prepending #. if your variable is named my_variable, its type is #my_variable. if you need to check if it's a big-integer type, simply do if #my_variable == #int. here is an example:
my_fn(x: #dbl, y: #dbl): #dbl
     average: #x = (x + y) * 0.5
     harmonic: #y = 2.0 / (x^-1 + y^-1)
     (average * harmonic)^0.5
note that normally you can just do average: (x + y) * 0.5 because oh-lang will infer types for you, but easy type reflection is there for you if you need it.

Comments