How can I get the actual type a generic function is called with?
The following example should print the type the given function f
returns:
def find[A](f: Int => A): Unit = {
print("type returned by f:" + ???)
}
If find
is called with find(x => "abc")
I want to get ""type returned by f: String". How can ???
be implemented in Scala 2.11?
Use a TypeTag
. When you require an implicit TypeTag
for a type parameter (or try to find one for any type), the compiler will automatically generate one and fill in the value for you.
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]
The above definition is equivalent to:
def find[A](f: Int => A)(implicit tt: TypeTag[A]): Unit = {
println("type returned by f: " + typeOf[A])
}
Use TypeTag
import scala.reflect.runtime.universe._
def func[A: TypeTag](a: A): Unit = println(typeOf[A])
scala> func("asd")
String
See more: http://docs.scala-lang.org/overviews/reflection/typetags-manifests.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With