#924 How do you get a reference to a specific object instance's method?

fury Sun 17 Jan 2010

If I have a string like:

a := "sample string"

is it possible to get a reference to a's ( not Str class method ) index method? I tried :

a#index
a#.index
#a.index
#a.index

and variations of adding .func to each of them. Couldn't get it working. I know I could do it with a closure, but I thought of asking if there's another way.

brian Sun 17 Jan 2010

sorry nothing like that today

the old & operator did that, but we decided to remove it until the feature can be tackled in a more uniform way in the future

msl Sun 17 Jan 2010

It's hardly as elegant as what you're trying to do (perhaps a suggestion for enhancement there), but:

Fantom Shell v1.0.48 ('?' for help)

fansh> s := "sample string"
sample string

// Verbose way - method("index") may throw a runtime error if "index" doesn't exist
fansh> f := Type.of(s).method("index").func.bind([s])
|sys::Str,sys::Int->sys::Int?|

// Concise way - Str#index won't compile if "index" doesn't exist
fansh> g := Str#index.func.bind([s])
|sys::Str,sys::Int->sys::Int?|

fansh> echo(s.index("e"))
5

fansh> echo(f.call("e"))
5

fansh> g.call("e")
5

It diverges from your wanting an instance's method rather than it's class's method though... I'm not sure if there's any way around that (or if it even matters - being statically typed, the object's type should always be a reasonable place to go to look up the method).

Login or Signup to reply.