[英]Strange Behaviour with Scala TypeTag Not Showing Type Arguments
I have the following code snippet: 我有以下代码片段:
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()
What I do not understand is that I was expecting the call paramInfo(Dummy(List(1,2)))
to actually print: 我不明白的是我期望调用paramInfo(Dummy(List(1,2)))
实际打印出来:
type of Dummy(List(1, 2)) has type arguments List(Dummy(List(Int)))
Did I get it wrong? 我弄错了吗? Any reason? 任何原因?
EDIT: After comments from Dima, I created a generic Dummy and this time I was expecting the type arguments to beList(Dummy(List(Int))), but it is not? 编辑:在Dima发表评论后,我创建了一个通用Dummy,这一次我期望类型参数为beList(Dummy(List(Int))),但是不是吗? Why? 为什么?
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)
So, args
in TypeRef
is a list of type parameters. 因此, TypeRef
中的args
是类型参数的列表。
Dummy
does not have type parameters, so you get a an empty List()
back. Dummy
没有类型参数,因此您会得到一个空的List()
。 List[Int]
has one type parameter - Int
- so, you get a list of a single element, which is Int
. List[Int]
具有一个类型参数Int
因此,您将获得一个元素的列表,即Int
。
I am not sure I understand why you were expecting to see what you said, so I can't help there ... why do you expect Dummy
to be a parameter to itself??? 我不确定我是否理解您为什么希望看到您说的话,所以我无济于事...为什么您希望Dummy
成为自身的参数?
BTW, you can write your match
statement shorter: 顺便说一句,您可以将您的match
语句写得更短:
val TypeRef(_, _, targs) = typeOf[N]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.