我有一个接受函数作为参数的方法。是否可以提取函数名称?
例如:

def plusOne(x:Int) = x+1
def minusOne(x:Int) = x+1

def printer(f: Int => Int) = println("Got this function ${f.getName}") //doesn't work of course

scala> printer(plusOne)
Got this function plusOne


scala> printer(minussOne)
Got this function minusOne

最佳答案

不直接。请注意,也可以传递lambda代替函数或方法名称。但是您可能想看看sourcecode库,它可以帮助您实现其中的一些功能。例如:

val plusOne = (x: Int) => x + 1
val minusOne = (x: Int) => x + 1

def printer(fWithSrc: sourcecode.Text[Int => Int]) = {
  val f = fWithSrc.value
  println(s"Got this function ${ fWithSrc.source }. f(42) = ${ f(42) }")
}


由于隐式转换的工作方式,因此不能像示例中那样直接使用def版本。如果您有这个:

def plusOne(x: Int) = x + 1


然后,您需要这样做:

printer(plusOne _)


并且您还将在参数的字符串表示形式中看到_

请注意,这也破坏了lambda的类型推断,即您不能再写以下代码了:

printer(_ * 2)


真可惜

09-05 19:35