How to get Scala function's parameters / return type?

强颜欢笑 提交于 2019-12-05 07:57:18

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

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

Just for completness, when you are in Scala REPL, you can access the type as:

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

scala> :type fn
(String, Double) => Int

At runtime, Scala compiler won't have complete type information. So it forms a code snippet fn, ( also does its own symbol table lookups ). https://github.com/scala/scala/blob/v2.10.5/src/compiler/scala/tools/nsc/interpreter/ILoop.scala#L449

Then passes it to the compiler which then attaches the type information to an implicit evidence type.

( explained here I want to get the type of a variable at runtime )

scala> import scala.reflect.runtime.universe.{TypeTag, typeTag}
import scala.reflect.runtime.universe.{TypeTag, typeTag}

scala> def getTypeTag[T: TypeTag](obj: T) = typeTag[T]
getTypeTag: [T](obj: T)(implicit evidence$1: reflect.runtime.universe.TypeTag[T])reflect.runtime.universe.TypeTag[T]

Now we have an evidence that will give us the exact type information:

scala> getTypeTag(fn)
res0: reflect.runtime.universe.TypeTag[(String, Double) => Int] = TypeTag[(String, Double) => Int]

scala> val targs = res0.tpe.typeArgs
targs: List[reflect.runtime.universe.Type] = List(String, Double, Int)

Now we can access the types with ease:

scala> val (in, out) = (ta.init, ta.last)
in: List[reflect.runtime.universe.Type] = List(String, Double)
out: reflect.runtime.universe.Type = Int

scala> println(s"INPUTS: $in")
INPUTS: List(String, Double)

scala> println(s"OUTPUT: $out")
OUTPUT: Int
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!