在println()中打印出函数的名称?

6 scala

我有一系列的功能.如何在println()函数中获取要打印的名称?在下面的代码中我得到这个输出:

<function2>
<function2>
<function2>

假设在我的真实代码中,我有更多具有更多描述性名称的函数.

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

}
Run Code Online (Sandbox Code Playgroud)

Lui*_*hys 6

Scala中的函数不具有描述性名称,只有Ints或Lists具有描述性名称; 你可以提出一个toString表示其价值的案例,但这不是一个名字.

但是,你可以Function2这样延伸:

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

这将按你的意愿行事.

或者更一般地说

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
}
Run Code Online (Sandbox Code Playgroud)

然后用作

val f1 = new NamedFunction2[Int, Int, Int]("f1", _ + _)
Run Code Online (Sandbox Code Playgroud)

等等