Note that there are some explanatory texts on larger screens.

plurals
  1. POScala TypeTags or Manifest: Is it possible to determine if a type is a Value class?
    text
    copied!<p>How do I find out if an object is a value class type, so that in the following example the test would print that the id is an AnyVal?</p> <pre><code>class MyId(val underlying: Int) extends AnyVal class AnyValSuite extends FunSuite { class Sample { def doIt[T](t: T)(implicit tag: TypeTag[T]): Unit = { if(???) println(s"$t is an AnyVal") } } test("Getting info if a type is a value class") { new Sample().doIt(new MyId(1)) } } </code></pre> <p>@senia: Thanks for the answer. Works perfect. Is it also possible to find out the primitive type the Value class is wrapping?</p> <p>Extended the example now:</p> <pre><code>class MyId(val underlying: Int) extends AnyVal class NonAnyValId(val underlying: Int) class AnyValSuite extends FunSuite { class Sample { def doIt[T](t: T)(implicit tag: TypeTag[T]): Unit = { if(implicitly[TypeTag[T]].tpe &lt;:&lt; typeOf[AnyVal]) println(s"$t is an AnyVal") else println(s"$t is not an AnyVal") } } test("Getting info if a type is a value class") { new Sample().doIt(new MyId(1)) new Sample().doIt(new NonAnyValId(1)) new Sample().doIt(1) } } </code></pre> <p>returns:</p> <pre><code>MyId@1 is an AnyVal NonAnyValId@38de28d is not an AnyVal 1 is an AnyVal </code></pre> <p><strong>Edit 2:</strong> Now with wrapped type checking:</p> <pre><code>import org.scalatest.FunSuite import scala.reflect.runtime.universe._ class MyId(val underlying: Int) extends AnyVal class NonAnyValId(val underlying: Int) class AnyValSuite extends FunSuite { class Sample { def doIt[T](t: T)(implicit tag: TypeTag[T]): Unit = { val tpe= implicitly[TypeTag[T]].tpe if(tpe &lt;:&lt; typeOf[AnyVal]) { println(s"$t is an AnyVal") val fields = tpe.members.filter(! _.isMethod) fields.size match { case 0 =&gt; println("has no fields, so it's a primitive like Int") case 1 =&gt; { println("has a sole field, so it's a value class") val soleValueClassField = fields.head.typeSignature println("of type: " + soleValueClassField) if(typeOf[Int] == soleValueClassField) println("It wraps a primitive Int") } case 2 =&gt; throw new Exception("should never get here") } } else println(s"$t is not an AnyVal") } } test("Getting info if a type is a value class") { new Sample().doIt(new MyId(1)) println new Sample().doIt(new NonAnyValId(1)) println new Sample().doIt(1) } } </code></pre> <p>returns:</p> <pre><code>MyId@1 is an AnyVal has a sole field, so it's a value class of type: Int It wraps a primitive Int NonAnyValId@3d0d4f51 is not an AnyVal 1 is an AnyVal has no fields, so it's a primitive like Int </code></pre> <p>Just wondering if there is some easier solution?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload