[英]In Scala 2.10, how do you create a ClassTag given a TypeTag
I'd like to define a function that returns an Array, and I have a TypeTag. 我想定义一个返回数组的函数,我有一个TypeTag。 Can I generate the required ClassTag? 我可以生成所需的ClassTag吗?
scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._
scala> def fun[X: TypeTag]: Array[X] = Array.ofDim[X](10)
<console>:11: error: No ClassTag available for X
def fun[X: TypeTag]: Array[X] = Array.ofDim[X](10)
Or is it necessary to provide implicit evidence of the ClassTag: 或者是否有必要提供ClassTag的隐含证据:
scala> import reflect.ClassTag
import reflect.ClassTag
scala> def fun[X: ClassTag: TypeTag]: Array[X] = Array.ofDim[X](10)(implicitly[ClassTag[X]])
fun: [X](implicit evidence$1: scala.reflect.ClassTag[X], implicit evidence$2: reflect.runtime.universe.TypeTag[X])Array[X]
I would have thought it simple to generate a ClassTag from a TypeTag, but I see no obvious way. 我认为从TypeTag生成ClassTag很简单,但我没有看到明显的方法。
I'd love to see a simpler solution, but here is what I came up with : 我希望看到一个更简单的解决方案,但这是我想出的:
def fun[X:TypeTag]: Array[X] = {
val mirror = runtimeMirror(getClass.getClassLoader)
implicit val xClassTag = ClassTag[X]( mirror.runtimeClass( typeTag[X].tpe ) )
Array.ofDim[X](10)
}
You'll want to make sure though that you really need to pass a TypeTag
in the first place. 你需要确保你真的需要首先传递一个TypeTag
。 Can't you pass a ClassTag
instead (as in def fun[X: ClassTag]
) ? 你不能通过ClassTag
(如def fun[X: ClassTag]
)吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.