I'm trying to dynamically cast an object in Fantom to the desired type chosen at runtime.
Type type := Int#
Obj n := 1 as Obj
echo((n as type).toStr)
This is a simplified example. I want to pass the type to a class and have it initialised when run.
A simple answer would be to just use a dynamic invoke, that is, use
->instead of.. If you know the method exists, then you don't even need to know the type:But more generally, you can't dynamically cast as you suggested. For if you don't know what
typeis at compile time, then how is the compiler supposed to know!?Usually
nwould implement a method that's defined on a parent supertype, you would then castnto that that supertype and call the method normally:But if there is no common parent type, then dynamic invoke is the way to go.
...or use reflection! It's a doddle in Fantom: