如何在Scala中获得泛型函数的实际类型?

dea*_*mon 2 generics reflection scala type-erasure

如何获得调用泛型函数的实际类型?

以下示例应打印给定函数f返回的类型:

def find[A](f: Int => A): Unit = {
  print("type returned by f:" + ???)
}
Run Code Online (Sandbox Code Playgroud)

如果使用find调用if ,find(x => "abc")我想获得“” f:String返回的类型。如何???在Scala 2.11中实现?

Tyt*_*yth 5

使用类型标签

import scala.reflect.runtime.universe._
def func[A: TypeTag](a: A): Unit = println(typeOf[A])

scala> func("asd")
String
Run Code Online (Sandbox Code Playgroud)

查看更多:http ://docs.scala-lang.org/overviews/reflection/typetags-manifests.html


Mic*_*jac 5

使用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]
Run Code Online (Sandbox Code Playgroud)

上面的定义等效于:

def find[A](f: Int => A)(implicit tt: TypeTag[A]): Unit = {
     println("type returned by f: " + typeOf[A])
}
Run Code Online (Sandbox Code Playgroud)

  • 注意,您需要添加scala-reflect.jar作为依赖项才能使用`TypeTag`。 (3认同)