[英]TypeTag for case classes
我想创建一个带有类型参数A
的案例类Bla
,它在运行时知道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)
有没有办法在下面的示例中进行编译? (或以其他方式实现相同的目标,即案例类是否意识到其类型参数的类型?)
为此,使用基于反射的API毫无意义,shapeless具有一个类型类,该类型类使用隐式宏将编译时信息公开给运行时。
import shapeless.Typeable
class Test[T : Typeable] {
def info: String = implicitly[Typeable[T]].describe
}
在这里滚动自己的东西也相对容易,这带来了额外的不便,即必须在与使用它的对象不同的其他编译单元中编译隐式宏。
您只需要将隐式类型标记参数传递给case类构造函数(否则,在调用需要它的paraInfo
之前,类型信息会丢失):
case class Bla[A : TypeTag]() { ... }
简写为:
case class Bla[A](implicit tag: TypeTag[A]) { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.