本文介绍了如何获取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部分所卡住-否则可能会进行一些难看的字符串解析.

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的一部分,该API不太了解Scala类型,您应该查看Scala Reflection 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函数的参数/返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 22:07