Reflection
Reflection obtains the following at runtime: what type a value is, what members it has, and what attributes are attached to its members. The entry point is the std::Reflect module’s typeof(T) syntax, which produces five non-constructible handle types: Type, Field, Prop, Attr, Method.
Reflection in the current version is mostly read-only; the only writable surface is field reads and writes. Dynamically invoking methods, constructing instances from a Type, assigning to props, and generating types dynamically are all outside the reflection surface for now.
Type: A Handle to a Type
typeof(T) produces the Type value for type T; Reflect.TypeOf(v) produces the runtime actual type of value v. Both live in the same domain and compare with each other via == and !=. When a declaration site holds a derived instance, TypeOf answers with the derived type:
class Base { public var a: int = 0; }
class Derived : Base { public var b: int = 0; }
func main() -> int
{
val b: Base = new Derived();
print(Reflect.TypeOf(b) == typeof(Derived), Reflect.TypeOf(b) != typeof(Base));
print(Reflect.TypeOf(42) == typeof(int));
return 0;
}True True
TrueTypeOf has a type answer for any value and never fails. Boxed scalars share the same key as static typeof; for Types with no member surface, discriminate with .Name.
| Value passed in | TypeOf result |
|---|---|
| Named-type instance / enum instance | The Type of that type |
| Boxed scalar (int / float / bool / string / char) | The matching scalar Type |
| Container (list / set / map / array) | Domain Type: "list", "set", "map", "array" |
| Vectors and colors | Domain Type: "vec2" through "color" |
Nullable with a value (int? holding 9) | The inner Type after stripping ? |
| null (including an empty nullable) | Domain Type: "null" |
| Error value / function value | Domain Type: "error" / "function" |
| Host-side unknown value | Domain Type: "external" |
A Type is a first-class value: storing it in a variable, passing it as an argument, and putting it in a list<Type> are all legal.
func AddOne(n: int) -> int
{
return n + 1;
}
func main() -> int
{
val xs: list<int> = [1, 2];
print(Reflect.TypeOf(xs).Name, Reflect.TypeOf(vec2(1.0, 2.0)).Name);
val has: int? = 9;
val none: int? = null;
print(Reflect.TypeOf(has) == typeof(int), Reflect.TypeOf(none).Name);
print(Reflect.TypeOf(null).Name, Reflect.TypeOf(AddOne).Name);
return 0;
}list vec2
True null
null function编写到此Written up to here
本页其余部分尚未完成,内容随时补充。The rest of this page is not written yet; more content will follow.
