Reputation: 1969
How can I get the simple class name including generic using TypeTag
? I think that the method signature should be like:
def getClassName[A: TypeTag](a: A): String
getClassName(Map("a" -> 123))
should return Map[String,Int]
.
Things I've tried:
def getClassName[A: TypeTag](a: A): String = {
typeOf[A].typeSymbol.name.toString
}
scala> getClassName(Map("a" -> 123))
res1: String = Map
def getClassName[A: TypeTag](a: A): String = {
typeOf[A].typeSymbol.toString
}
scala> getClassName(Map("a" -> 123))
res1: String = trait Map
def getClassName[A: TypeTag](a: A): String = {
typeOf[A].toString
}
scala> getClassName(Map("a" -> 123))
res1: String = scala.collection.immutable.Map[String,Int] // It knows the full type!
def getClassName[A: TypeTag](a: A): String = {
typeOf[A].typeSymbol.fullName
}
scala> getClassName(Map("a" -> 123))
res1: String = scala.collection.immutable.Map
Upvotes: 2
Views: 1327
Reputation: 1969
I'll add my answers to this based on Artem Aliev's answer, since it doesn't seems like Scala has this built-in. This method uses context bound syntax instead of an implicit parameter.
def getClassName[A: TypeTag](a: A): String = {
val typeArgs = typeOf[A].typeArgs
s"${typeOf[A].typeSymbol.name}${if (typeArgs.nonEmpty) typeArgs.mkString("[",",", "]") else ""}"
}
scala> getClassName(Map("a" -> 123))
res1: String = Map[String,Int]
Upvotes: 1
Reputation: 1407
From here: https://docs.scala-lang.org/overviews/reflection/typetags-manifests.html
import scala.reflect.runtime.universe._
def getClassName[T](x: T)(implicit tag: TypeTag[T]): String = {
tag.tpe match { case TypeRef(_, t, args) => s"""${t.name} [${args.mkString(",")}]""" }
}
getClassName(Map("a" -> 123))
res5: String = Map [java.lang.String,Int]
UPDATE: Shorter version with full class names
def getClassName[T: TypeTag](x: T) = typeOf[T].toString
getClassName(Map("a" -> 123))
res1: String = scala.collection.immutable.Map[java.lang.String,Int]
Upvotes: 2