作者:瓦斯的2010_217 | 来源:互联网 | 2023-02-01 20:05
我有一个接受函数作为参数的方法。是否可以提取函数名称?例如:
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
Jean-Philipp..
5
不直接。请注意,也可以传递lambda代替函数或方法名称。但是您可能需要查看源代码库,这可能有助于您实现其中的一些功能。例如:
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 _)
并且您还将_
在参数的String表示中看到。
请注意,这也破坏了lambda的类型推断,即,您不能再写这个了:
printer(_ * 2)
真可惜
1> Jean-Philipp..:
不直接。请注意,也可以传递lambda代替函数或方法名称。但是您可能需要查看源代码库,这可能有助于您实现其中的一些功能。例如:
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 _)
并且您还将_
在参数的String表示中看到。
请注意,这也破坏了lambda的类型推断,即,您不能再写这个了:
printer(_ * 2)
真可惜