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
?
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.
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 ( . )
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With