更新时间:2022-12-31 10:41:15
不是直接的.请注意,也可以传递 lambda 而不是函数或方法名称.但是你可能想看看sourcecode 库,它可能会帮助你实现其中一些.例如:
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) }")
}
由于隐式转换的工作方式,您不能像示例中那样直接使用 def
版本.如果你有这个:
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
那么你需要这个:
printer(plusOne _)
并且您还将在参数的字符串表示中看到 _
.
and you'll also see the _
in the String representation of the parameter.
请注意,它也破坏了 lambda 的类型推断,也就是说,您不能再这样写了:
Note that it also breaks type inference for lambdas, i.e., you can't write this any more:
printer(_ * 2)
这是一种耻辱.