user568866
user568866

Reputation:

Printing out a function's name in println()?

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());
   }

}

Upvotes: 6

Views: 2870

Answers (2)

Luigi Plinge
Luigi Plinge

Reputation: 51109

Functions in Scala don't have descriptive names any more than Ints or Lists have descriptive names; you could make a case for toString giving a representation of its value, but that wouldn't be a name.

You could, however, extend Function2 thus:

object f1 extends Function2[Int, Int, Int] {
  def apply(a: Int, b: Int) = a + b
  override def toString = "f1"
}

which will act as you want.

Or more generally

class NamedFunction2[T1,T2,R](name: String, f: Function2[T1,T2,R]) 
                                       extends Function2[T1,T2,R] {
  def apply(a: T1, b: T2): R = f.apply(a, b)
  override def toString = name
}

then use as

val f1 = new NamedFunction2[Int, Int, Int]("f1", _ + _)

etc.

Upvotes: 6

Rex Kerr
Rex Kerr

Reputation: 167891

You can't; the name is lost during conversion from a method to a Function2.

Upvotes: 2

Related Questions