vendredi 16 septembre 2016

Can I check if a Scala object is of a given type is this type is a boxed primitive?

I'm trying to define a function to check if an object is of a given type using reflection :

implicit class NoEraseInstanceOf(that: Any) {
  def noEraseInstanceOf[T: ClassTag]= {
    val targetClass = classTag[T]
    targetClass.runtimeClass.isInstance(that)
  }
}

It is working fine with most of types, but not with boxed primitive types like Int. Due to runtime type, an Int is seen as a java Integer for example :

scala> val i = 1
i: Int = 1

scala> i.noEraseInstanceOf[Int]
res1: Boolean = false

scala> i.noEraseInstanceOf[Integer]
res2: Boolean = true

Is there a way to achieve this?

Thanks :)





Aucun commentaire:

Enregistrer un commentaire