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.
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]
) ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With