Scala TypeTag不显示类型参数的奇怪行为
我有以下代码片段:Scala TypeTag不显示类型参数的奇怪行为,scala,Scala,我有以下代码片段: import scala.reflect.runtime.universe._ def paramInfo[N: TypeTag](x: N): Unit = { val targs = typeOf[N] match { case TypeRef(_, _, args) => args } println(s"type of $x has type arguments $targs") } case class Dummy(l: List[Int]) i
import scala.reflect.runtime.universe._
def paramInfo[N: TypeTag](x: N): Unit = {
val targs = typeOf[N] match { case TypeRef(_, _, args) => args }
println(s"type of $x has type arguments $targs")
}
case class Dummy(l: List[Int])
import scala.reflect.runtime.universe._
paramInfo: [N](x: N)(implicit evidence$1: reflect.runtime.universe.TypeTag[N])Unit
defined class Dummy
// Exiting paste mode, now interpreting.
type of Dummy(List(1, 2)) has type arguments List()
scala> paramInfo(List(1,2))
type of List(1, 2) has type arguments List(Int)
scala> paramInfo(Dummy(List(1,2)))
type of Dummy(List(1, 2)) has type arguments List()
我不明白的是,我期望调用paramInfo(Dummy(List(1,2))
实际打印:
type of Dummy(List(1, 2)) has type arguments List(Dummy(List(Int)))
我弄错了吗?有什么原因吗
编辑:在Dima的注释之后,我创建了一个泛型伪,这次我希望类型参数是beList(Dummy(List(Int)),但不是吗?为什么?
scala> case class Dummy[X](l: List[X])
defined class Dummy
scala> Dummy[Int](List(1,2))
res64: Dummy[Int] = Dummy(List(1, 2))
scala> paramInfo(res64)
type of Dummy(List(1, 2)) has type arguments List(Int)
因此,
TypeRef
中的args
是类型参数列表
Dummy
没有类型参数,因此返回一个空的列表()。
List[Int]
有一个类型参数-Int
-因此,可以得到单个元素的列表,即Int
我不知道我是否理解你为什么期待看到你说的话,所以我无法帮助你。。。为什么希望Dummy
本身就是一个参数
顺便说一句,你可以把你的match
语句写得更短:
val TypeRef(_, _, targs) = typeOf[N]
我已经编辑了我的帖子。你现在可以看一看并给我一些解释吗?他们输入了你新更新的Dummy
的参数是Int
。因此,TypeRef
中的args
是一个列表(Int)
。我仍然不明白你为什么期待它前面的List(Dummy(…
东西。Dummy
不是Dummy
的参数。