scala get function name that was sent as param

2019-08-03 21:00发布

问题:

I have a method that accepts a function as a param. is it possible to extract the function name ? e.g:

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

回答1:

Not directly. Note that a lambda could be passed as well instead of a function or method name. But you may want to look at the sourcecode library, which may help you achieve some of this. For instance:

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) }")
}

Due to the way implicit conversions work, you cannot use the def version directly as in your example. If you have this:

def plusOne(x: Int) = x + 1

Then you need this:

printer(plusOne _)

and you'll also see the _ in the String representation of the parameter.

Note that it also breaks type inference for lambdas, i.e., you can't write this any more:

printer(_ * 2)

which is a shame.



标签: scala