如何获取 Scala 函数的参数/返回类型? [英] How to get Scala function's parameters / return type?

查看:27
本文介绍了如何获取 Scala 函数的参数/返回类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,想获取它的参数类型和返回类型,以便在 Scala 宏中使用.

I have a function, and would like to obtain its parameter types and return type for use in Scala macros.

scala> val fn = (a: String, b: Double) => 123
fn: (String, Double) => Int = <function2>

scala> fn.getClass
res1: Class[_ <: (String, Double) => Int] = class $anonfun$1

在上面的例子中,参数类型和返回类型已经在两行打印出来,但我不知道如何访问它们.即使使用 toString,我也会被 <function2>class $anonfun$1 部分困住 = sign -- 否则可能会进行一些难看的字符串解析.

In the above example, the parameter types and return type already get printed at both lines, but I don't know how to access them. Even with toString I'd be stuck with the <function2> and class $anonfun$1 parts right of the = sign -- otherwise a bit of ugly string parsing might have done.

我发现 MethodSymbolApi 提供了一种为方法提取此信息的方法,但对于这种特殊情况,这似乎无济于事.

I found that the MethodSymbolApi offers a way to extract this information for methods, but it seems like this might not help for this particular case.

我目前正在研究 AST 解析(作为 scala.meta 的一部分)以提取信息,但我认为这个问题看起来足够基本,可以被标准反射库覆盖,虽然我没能在里面找到我想要的东西.有什么想法吗?

I'm currently looking into AST parsing (as part of scala.meta) to extract the information, but I'd think this question would seem basic enough to be covered by the standard reflection library, though I've failed to find what I want in there. Any ideas?

根据@johanandren 的回答进行

Edit based on @johanandren's answer:

我还没有找到一种更简洁的方法来从 TypeTag/Type 中提取它们,但这确实有效.:)

I haven't found a neater way to extract them from the TypeTag/Type yet, but this does already work. :)

scala> val fn = (a: String, b: Double) => 123
scala> import scala.reflect.runtime.{universe => ru}
scala> def getTypeTag[T: ru.TypeTag](obj: T) = ru.typeTag[T]
scala> getTypeTag(fn).tpe.toString.split(" => ")
res179: Array[String] = Array((String, Double), Int)

推荐答案

getClass 是 Java 反射 API 的一部分,它不太了解 Scala 类型,您应该查看 Scala 反射 API.这应该会让你开始,http://docs.scala-lang.org/overviews/reflection/overview.html

getClass is part of the Java reflection API which does not quite understand Scala types, you should look at the Scala Reflection API instead. This should get you started, http://docs.scala-lang.org/overviews/reflection/overview.html

不确定,但我认为函数类型的 TypeTag 是您想要的.

Not sure but I think a TypeTag for the function type is what you want.

这篇关于如何获取 Scala 函数的参数/返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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