mixel - 7 months ago 42

Scala Question

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

`Class[java.lang.Integer]`

`Class[Int]`

`Class[java.lang.Float]`

`Class[Float]`

I mean this kind of function:

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

Answer

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.

Source (Stackoverflow)