mixel mixel - 1 year ago 93
Scala Question

Get class of boxed type from class of primitive type

If I have value:

val i: Int = 1

I can get its class:

> i.getClass
res1: Class[Int] = int

and class of boxed value:

> i.asInstanceOf[AnyRef].getClass
res2: Class[_ <: AnyRef] = class java.lang.Integer

The question is how to get class of boxed type from class of any primitive type without having a value, for example it should return
and so on?

I mean this kind of function:

def boxedClass[T]: Class[AnyRef] = ...

Answer Source

This seems to work in scala 2.11.x and 2.12.x, a little bit to my own surprise.

scala> import scala.reflect.ClassTag
import scala.reflect.ClassTag

scala> class Boxed[T <: AnyVal] { def apply[R <: AnyRef]()(implicit conv: T => R, tag: ClassTag[R]) = tag.runtimeClass }
defined class Boxed

scala> def boxedClass[T <: AnyVal] = new Boxed[T]
boxedClass: [T <: AnyVal]=> Boxed[T]

scala> boxedClass[Int]()
res5: Class[_] = class java.lang.Integer

scala> boxedClass[Double]()
res6: Class[_] = class java.lang.Double

It works by fixing T to the type you want the boxed class of, and then looking for a conversion of T to a type R that is a subtype of AnyRef. Then you take the ClassTag[R] and you have the class you're looking for.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download