Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 363
Adam Klein Avatar asked Feb 26 '13 17:02

Adam Klein


1 Answers

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

like image 98
Régis Jean-Gilles Avatar answered Oct 02 '22 13:10

Régis Jean-Gilles