First, note that your isObjectOfValueClass
will get a boxed version of your value class instances.
Second, it cannot work like you want. It's because classOf[AnyVal] == classOf[AnyRef] == <java.lang.Object>
.
There's no runtime way to distinguish between a boxed value class and a reference class (Any
doesn't have .instanceOf[T]
, AnyVal
cannot be used in pattern matching or as parameter of .instanceOf[T]
, and what's most important, compiled value classes do not extend or implement AnyVal
).
If you want it decided on compile time, then try:
case class IsAnyVal[-T](val value: Boolean) extends AnyVal
implicit def _noClueHowToNameThisImplicit_1 = IsAnyVal[AnyVal](true)
implicit def _noClueHowToNameThisImplicit_2 = IsAnyVal[AnyRef](false)
def isAnyVal[T](arg: T)(implicit ev: IsAnyVal[T]) = ev.value
scala> isAnyVal(1)
res4: Boolean = true
scala> isAnyVal("")
res5: Boolean = false
I'm not sure how you want to extract the sole field of the detected boxed value class instances without more accidental boxing. Besides, Hotspot is pretty good at optimizing small short-lived objects.