你可以使用ClassTag
.
val string = implicitly[ClassTag[String]]
def getValue[T : ClassTag] =
implicitly[ClassTag[T]] match {
case `string` => "String"
case ClassTag.Int => "Int"
case _ => "Other"
}
或者TypeTag
:
import scala.reflect.runtime.universe.{TypeTag, typeOf}
def getValue[T : TypeTag] =
if (typeOf[T] =:= typeOf[String])
"String"
else if (typeOf[T] =:= typeOf[Int])
"Int"
else
"Other"
用法:
scala> getValue[String]
res0: String = String
scala> getValue[Int]
res1: String = Int
scala> getValue[Long]
res2: String = Other
如果您正在使用2.9.x
,您应该使用Manifest
:
import scala.reflect.Manifest
def getValue[T : Manifest] =
if (manifest[T] == manifest[String])
"String"
else if (manifest[T] == manifest[Int])
"Int"
else
"Other"