如何在 Scala 中获取泛型函数的实际类型?
How to get the actual type of a generic function in Scala?
如何获取调用泛型函数的实际类型?
以下示例应打印给定函数的类型 f
returns:
def find[A](f: Int => A): Unit = {
print("type returned by f:" + ???)
}
如果用 find(x => "abc")
调用 find
我想得到“"type returned by f: String"。如何在 Scala 2.11 中实现 ???
?
使用类型标签
import scala.reflect.runtime.universe._
def func[A: TypeTag](a: A): Unit = println(typeOf[A])
scala> func("asd")
String
查看更多:http://docs.scala-lang.org/overviews/reflection/typetags-manifests.html
使用 TypeTag
。当您需要类型参数的隐式 TypeTag
(或尝试为任何类型寻找一个)时,编译器将自动生成一个并为您填充值。
import scala.reflect.runtime.universe.{typeOf, TypeTag}
def find[A: TypeTag](f: Int => A): Unit = {
println("type returned by f: " + typeOf[A])
}
scala> find(x => "abc")
type returned by f: String
scala> find(x => List("abc"))
type returned by f: List[String]
scala> find(x => List())
type returned by f: List[Nothing]
scala> find(x => Map(1 -> "a"))
type returned by f: scala.collection.immutable.Map[Int,String]
以上定义等同于:
def find[A](f: Int => A)(implicit tt: TypeTag[A]): Unit = {
println("type returned by f: " + typeOf[A])
}
如何获取调用泛型函数的实际类型?
以下示例应打印给定函数的类型 f
returns:
def find[A](f: Int => A): Unit = {
print("type returned by f:" + ???)
}
如果用 find(x => "abc")
调用 find
我想得到“"type returned by f: String"。如何在 Scala 2.11 中实现 ???
?
使用类型标签
import scala.reflect.runtime.universe._
def func[A: TypeTag](a: A): Unit = println(typeOf[A])
scala> func("asd")
String
查看更多:http://docs.scala-lang.org/overviews/reflection/typetags-manifests.html
使用 TypeTag
。当您需要类型参数的隐式 TypeTag
(或尝试为任何类型寻找一个)时,编译器将自动生成一个并为您填充值。
import scala.reflect.runtime.universe.{typeOf, TypeTag}
def find[A: TypeTag](f: Int => A): Unit = {
println("type returned by f: " + typeOf[A])
}
scala> find(x => "abc")
type returned by f: String
scala> find(x => List("abc"))
type returned by f: List[String]
scala> find(x => List())
type returned by f: List[Nothing]
scala> find(x => Map(1 -> "a"))
type returned by f: scala.collection.immutable.Map[Int,String]
以上定义等同于:
def find[A](f: Int => A)(implicit tt: TypeTag[A]): Unit = {
println("type returned by f: " + typeOf[A])
}