【问题标题】:How to get the actual type of a generic function in Scala?如何在 Scala 中获取泛型函数的实际类型?
【发布时间】:2015-11-20 14:39:30
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: scala generics reflection type-erasure


    【解决方案1】:

    使用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])
    }
    

    【讨论】:

    • 请注意,您需要添加 scala-reflect.jar 作为依赖项才能使用TypeTag
    【解决方案2】:

    使用类型标签

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-04
      • 2018-08-18
      • 2017-06-07
      • 1970-01-01
      • 2016-07-15
      • 2013-09-13
      相关资源
      最近更新 更多