开发者

Scala - get function name

开发者 https://www.devze.com 2023-04-11 16:31 出处:网络
I have a function foo w开发者_StackOverflow社区hich takes another function (say bar) as a parameter. Is there a way to get the function name of bar as a string inside foo?No. See the difference betwee

I have a function foo w开发者_StackOverflow社区hich takes another function (say bar) as a parameter. Is there a way to get the function name of bar as a string inside foo?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号