scala 获取作为参数发送的函数名称

2023-12-04

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

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,而不是传递函数或方法名称。但您可能想看看源代码库,它可以帮助您实现其中一些目标。例如:

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)

这是一种耻辱。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

scala 获取作为参数发送的函数名称 的相关文章

随机推荐