In Scala 2.10, how do you create a ClassTag given a TypeTag

谁说我不能喝 提交于 2019-12-21 03:52:07

问题


I'd like to define a function that returns an Array, and I have a TypeTag. Can I generate the required 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:

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.


回答1:


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. Can't you pass a ClassTag instead (as in def fun[X: ClassTag]) ?



来源:https://stackoverflow.com/questions/15095727/in-scala-2-10-how-do-you-create-a-classtag-given-a-typetag

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!