23. The Any Type
The Any type wraps a value of any type into a uniform runtime object, enabling heterogeneous collections
and dynamic type dispatch. The wrapped value retains its original type, which can be tested at runtime.
23.1 Wrapping Values
Use the any() function to wrap a value. The result prints as Any(value, Type).
let a = any(5);
a println; -- Any(5, Int)
let b = any("hello");
b println; -- Any(hello, String)
let c = any(3.14);
c println; -- Any(3.14, Float)
let d = any('foo);
d println; -- Any('foo, Symbol)
any(true) println; -- Any(true, Bool)
23.2 Type Testing with as(Type)
The postfix as(Type) operator tests whether an Any value wraps the given type.
It returns Option<T> — some(value) if the type matches, none otherwise.
let a = any(5);
a as(Int) println; -- Option<Int>.some(5)
a as(String) println; -- Option<String>.none
let b = any("hello");
b as(String) println; -- Option<String>.some(hello)
23.3 Pattern Matching on Any
In a match expression, use name Type patterns to test the wrapped type and bind
the unwrapped value to a name. Use _ as a catch-all for unmatched types.
fn describe(x Any) String {
match(x) {
i Int: "int: " $ toString(i);
s String: "string: " $ s;
f Float: "float: " $ toString(f);
_: "other";
}
}
describe(any(42)) println; -- int: 42
describe(any("hi")) println; -- string: hi
describe(any(2.7)) println; -- float: 2.7
describe(any('x)) println; -- other
23.4 Heterogeneous Arrays
Use any() with multiple arguments or toAnyArray on a tuple to create an [Any]
— an array where each element can be a different type.
-- Variadic any() wraps each arg and returns [Any]
any(1, "two", 'three, 4.0) println;
-- [Any(1, Int), Any(two, String), Any('three, Symbol), Any(4.0, Float)]
-- toAnyArray converts a tuple to [Any]
(1, "two", 'three, 4.0) toAnyArray println;
-- [Any(1, Int), Any(two, String), Any('three, Symbol), Any(4.0, Float)]
-- Nested any calls
any(1, any(2, 3)) println;
-- [Any(1, Int), Any([Any(2, Int), Any(3, Int)], [Any])]