基于阅读
Scala 获得的 TypeTag 知识的示例:什么是 TypeTag 以及如何使用它?Eugene Burmako在对您的问题的评论中
发布
:
import scala.reflect.runtime.universe._
object ScalaApplication {
def main(args: Array[String]) {
printType(List(42))
printType(List("42"))
printType(List("42", 42))
}
def printType[T : TypeTag](t: T) {
println(typeOf[T])
}
}
这应该给出输出:
$ scala ScalaApplication.scala
List[Int]
List[String]
List[Any]
[更新1:]
但是,如果您想知道分配给类型引用的类型Any
,您可能必须选择某种类型感知包装器:
import scala.reflect.runtime.universe._
object ScalaApplication {
def main(args: Array[String]) {
val anyWrapper = new AnyWrapper
List(1,2,3).foreach { i =>
i match {
case 1 => anyWrapper.any = 42
case 2 => anyWrapper.any = "a string"
case 3 => anyWrapper.any = true
}
print(anyWrapper.any)
print(" has type ")
println(anyWrapper.typeOfAny)
}
}
class AnyWrapper {
private var _any: Any = null
private var _typeOfAny: Type = null
def any = _any
def typeOfAny = _typeOfAny
def any_=[T: TypeTag](a: T) = {
_typeOfAny = typeOf[T]
_any = a
}
}
}
这应该给出输出:
$ scala ScalaApplication.scala
42 has type Int
a string has type String
true has type Boolean
但是这个解决方案仍然没有涵盖在编译时引用类型未知的情况。
[更新 2:]
如果将类型显式转换为 type 的引用Any
,则可能必须在 match 语句中枚举所有可能的类型才能恢复类型:
import scala.reflect.runtime.universe._
object ScalaApplication {
def main(args: Array[String]) {
List(1,2,3).foreach { i =>
val any: Any = i match {
case 1 => 42.asInstanceOf[Any]
case 2 => "a string".asInstanceOf[Any]
case 3 => true.asInstanceOf[Any]
}
print(any)
print(" has type ")
println(matchType(any))
}
}
def matchType(any: Any) = {
any match {
case a: Int => typeOf[Int]
case a: String => typeOf[String]
case a: Boolean => typeOf[Boolean]
}
}
}
这应该给出输出:
$ scala ScalaApplication.scala
42 has type Int
a string has type String
true has type Boolean
但是此解决方案要求您了解(并列出)您可以在any
值中收到的所有可能类型。