Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - get function name

Tags:

scala

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?

like image 670
jeffreyveon Avatar asked Oct 06 '11 07:10

jeffreyveon


People also ask

How do I print a function name in scala?

Print,Println,Printf Go to Spark-shell or choose environment of your choice to run scala code. If you type print and press the tab ,you can see three functions ,Related to print ,these are print,printf and println.

What do you call a function defined in a block in scala?

A method is a function defined in a class and available from any instance of the class. The standard way to invoke methods in Scala (as in Java and Ruby) is with infix dot notation, where the method name is prefixed by the name of its instance and the dot ( . )

What is difference between function and method in scala?

Difference between Scala Functions & Methods: Function is a object which can be stored in a variable. But a method always belongs to a class which has a name, signature bytecode etc. Basically, you can say a method is a function which is a member of some object.


2 Answers

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.

like image 121
axel22 Avatar answered Oct 04 '22 00:10

axel22


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.

like image 36
Duncan McGregor Avatar answered Oct 04 '22 01:10

Duncan McGregor