scala 获取作为参数发送的函数名称 [英] scala get function name that was sent as param

查看:42
本文介绍了scala 获取作为参数发送的函数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

不是直接的.请注意,也可以传递 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)

这是一种耻辱.

这篇关于scala 获取作为参数发送的函数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆