3

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.

candronikos
  • 159
  • 1
  • 13

1 Answers1

3

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:

n := (Obj) 1
echo( n->toStr() )

But more generally, you can't dynamically cast as you suggested. For if you don't know what type is at compile time, then how is the compiler supposed to know!?

Usually n would implement a method that's defined on a parent supertype, you would then cast n to that that supertype and call the method normally:

myObj := ...
n := (Supertype) myObj
n.myMethod()

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:

n := (Obj) 1
method := n.typeof.method("toStr")
echo( method.callOn(n, null) )
Steve Eynon
  • 4,979
  • 2
  • 30
  • 48