我想提出一个案例类Bla
,它采用类型参数A
,它在运行时知道A
的类型(它将其存储在其info
字段中)。TypeTag用于案例分类
我的尝试如下例所示。问题是这个例子不能编译。
case class Bla[A](){
val info=Run.paramInfo(this) // this does not compile
}
import scala.reflect.runtime.universe._
object Run extends App{
val x=Bla[Int]
def paramInfo[T](x:T)(implicit tag: TypeTag[T]): String = {
val targs = tag.tpe match { case TypeRef(_, _, args) => args }
val tinfo=s"type of $x has type arguments $targs"
println(tinfo)
tinfo
}
paramInfo(x)
}
然而,当我评论val info=Run.paramInfo(this)
然后该程序运行正常,并打印:
型血乳酸(的)有类型参数列表(INT)
有没有一种方法,使这个例子下面编译? (或以某种其他方式实现相同的目标,即案例类是自我意识到它的类型参数的类型?)
谢谢,这工作。 – jhegedus