有没有办法获取函数的字符串表示形式?
val f = List(1, 2, 3, 4, 66, 11).foldLeft(55)_
f
是 ((Int, Int) => Int) => Int
类型的函数,这就是我正在寻找的表示形式,但我无法在任何地方找到它。
toString
方法是我的第一次尝试,当然,但它返回的只是<function1>
. scala REPL 做得对,文档也是。一定有办法吗?
问候。
最佳答案
当类型在编译时已知时,您可以使用 Scalas TypeTag
:
scala> import reflect.runtime.universe._
import reflect.runtime.universe._
scala> def typeRep[A : TypeTag](a: A) = typeOf[A]
typeRep: [A](a: A)(implicit evidence$1: reflect.runtime.universe.TypeTag[A])reflect.runtime.universe.Type
scala> val f = List(1, 2, 3, 4, 66, 11).foldLeft(55)_
f: ((Int, Int) => Int) => Int = <function1>
scala> typeRep(f)
res2: reflect.runtime.universe.Type = ((Int, Int) => Int) => Int
有关 TypeTag
正在做什么的详细说明,请参阅 another回答。
关于string - Scala,函数的字符串表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14426167/