I have an array of functions. How can I get the names to print in a println() function? In the code below I just get this output:
<function2>
<function2>
<function2>
Assume that in my real code I have a lot more functions with more descriptive names.
def printNames() {
def f1(x: Int, y: Int): Int = x + y
def f2(x: Int, y: Int): Int = x - y
def f3(x: Int, y: Int): Int = x * y
val fnList = Array(f1 _, f2 _, f3 _)
for (f <- fnList) {
println(f.toString());
}
}
Functions in Scala don’t have descriptive names any more than Ints or Lists have descriptive names; you could make a case for
toStringgiving a representation of its value, but that wouldn’t be a name.You could, however, extend
Function2thus:which will act as you want.
Or more generally
then use as
etc.