Adam Klein
Adam Klein

Reputation: 476

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. 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.

Upvotes: 11

Views: 2262

Answers (1)

R&#233;gis Jean-Gilles
R&#233;gis Jean-Gilles

Reputation: 32719

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]) ?

Upvotes: 8

Related Questions