12

I have a function foo which takes another function (say bar) as a parameter. Is there a way to get the function name of bar as a string inside foo?

jeffreyveon
  • 13,400
  • 18
  • 79
  • 129
  • 2
    What exactly do you mean by "the name" of the function? – agilesteel Oct 06 '11 at 07:32
  • Say I pass a function called bar into foo. Inside foo, I receive this function with a parameter call baz. I want to print "bar", i.e. the name of the function passed in. – jeffreyveon Oct 06 '11 at 07:42
  • Am I getting it right? You actually want the reference `bar`, which referred to the function before it was passed into the scope of `foo` as a parameter and became `baz`. If so, then there is no way in hell you could do that. – agilesteel Oct 06 '11 at 07:49
  • 1
    I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question. – Tom Crockett Oct 06 '11 at 08:35
  • 1
    @agilesteel - I am basically looking to do something like a toString on the parameter passed in to get "bar". Don't think it's possible looking at the other answers.. – jeffreyveon Oct 06 '11 at 08:55
  • 2
    If you describe the reason why you want to do this, you might get some useful alternative solutions. – Jesper Nordenberg Oct 06 '11 at 10:38

2 Answers2

15

No. See the difference between methods and functions. Methods aren't passed as parameters under the hood - they are expanded into function objects when being passed to some other method/function. These function objects are instances of anonymous, compiler-generated classes , and have no name (or, at least, being anonymous classes, have some mangled name which you could access using reflection, but probably don't need).

So, when you do:

def foo() {}

def bar(f: () => Unit) {}

bar(foo)

what actually happens in the last call is:

bar(() => foo())

Theoretically, though, you could find the name of the method that the function object you're being passed is wrapping. You could do bytecode introspection to analyze the body of the apply method of the function object f in method bar above, and conclude based on that what the name of the method is. This is both an approximation and an overkill, however.

Community
  • 1
  • 1
axel22
  • 32,045
  • 9
  • 125
  • 137
2

I've had quite a dig around, and I don't think that there is. toString on the function object just says eg <function1>, and its class is a synthesised class generated by the compiler rather that something with a method object inside it that you might query.

I guess that if you really needed this there would be nothing to stop you implementing function with something that delegated but also knew the name of the thing to which it was delegating.

Duncan McGregor
  • 17,665
  • 12
  • 64
  • 118