32. Appendix
Type Inference
This section formally defines the rules for how the compiler performs type inference on lists, maps, and the ternary operator:
// list of expressions [v1, v2, ...] => V = common(v1, v2, ...) // map of expressions [k1:v1, k2:v2, ...] => K = common(k1, k2, ...) V = common(v1, v2, ...) // ternary operator cond ? t1 : t2 => common(t1, t2)
Type inference of collections is based on a function we call common which is used to find the most common base class among a list of types. The following algorithm is used to compute the common type:
- if the list of types is empty return
Obj?
- if the list of types has only one item, return that type
- if any one type is nullable, then the result is nullable
- if none of the types is a parameterized generic, then find the most common class which all the types share; we take only classes into account, mixins are ignored
- if any one of the types is a parameterized generic then:
- if all the types are parameterized Lists, then compute the common V type
- if all the tyeps are parameterized Maps then:
- if all have the exact same signature, then use that type
- use
sys::Map
- if all the types are parameterized Funcs then:
- if all have the exact same signature, then use that type
- use
sys::Func
- if none of the above holds true, then use
Obj