Scala TypeTags或Manifest:是否可以确定类型是否为Value类?

时间:2013-11-14 16:44:08

标签: scala

如何确定对象是否为值类类型,以便在以下示例中测试将打印出id为AnyVal?

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))
  }
}

@senia:谢谢你的回答。工作完美。是否也可以找出Value类包装的原始类型?

现在扩展示例:

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 <:< 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)
  }
}

返回:

MyId@1 is an AnyVal
NonAnyValId@38de28d is not an AnyVal
1 is an AnyVal

编辑2: 现在进行包装类型检查:

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 <:< typeOf[AnyVal])  {
        println(s"$t is an AnyVal")
        val fields = tpe.members.filter(! _.isMethod)

        fields.size  match {
          case 0 => println("has no fields, so it's a primitive like Int")
          case 1 => {
            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 => 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)
  }
}

返回:

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

只是想知道是否有更简单的解决方案?

1 个答案:

答案 0 :(得分:5)

您只需检查TAnyVal的子类型。

import scala.reflect.runtime.universe.{TypeTag, typeOf}

def doIt[T: TypeTag](t: T): Unit = {
  if(implicitly[TypeTag[T]].tpe <:< typeOf[AnyVal]) println(s"$t is an AnyVal")     
}

doIt(new MyId(1))
// $line18.$read$$iw$$iw$$iw$$iw$MyId@1 is an AnyVal
相关问题