Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the actual type of a generic function in Scala?

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?

like image 495
deamon Avatar asked Dec 25 '22 15:12

deamon


2 Answers

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])
}
like image 102
Michael Zajac Avatar answered Dec 28 '22 06:12

Michael Zajac


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

like image 20
Tyth Avatar answered Dec 28 '22 07:12

Tyth