【发布时间】:2017-09-05 20:31:31
【问题描述】:
我想创建一个案例类Bla,它接受一个类型参数A,它在运行时知道A 的类型(它将它存储在它的info 字段中)。
我的尝试如下例所示。问题是这个例子没有编译。
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) 时,程序运行良好并打印:
Bla() 的类型具有类型参数 List(Int)
有没有办法让下面的这个例子编译? (或者以其他方式实现相同的目标,即一个案例类是自我意识到它的类型参数的类型?)
【问题讨论】:
标签: scala reflection case-class scala-reflect reify