Scala:如何检查 Array[T] 的类型

Scala: How to check the type of Array[T]

我有一个Array[T],如何查看它的类型?

我试过了

def check[T](a: Array[T]) = {
  a match {
    case _: Array[Int] => // create type specified IntVector
    case _: Array[Float] => // create type specified FloatVector
  }
}

编译器引发错误

Scrutinee is incompatible with pattern type, found: Array[Int], required: Array[T]

我之所以要这样做是因为假设我可以枚举出所有的类型,而目前只有Int和Float

def check[T](a: Array[T]) = {
  val base: Base = baseVector
  val derived = a match {
    case _: Array[Int] => base.asInstanceOf[IntVector]      
    case _: Array[Float] => base.asInstanceOf[FloatVector]
  }
  derived.run()
}
abstract class Base
  def run()
class IntVector extends Base
  override def run()
class FloatVector extends Base
  override def run()

这对我有用:

def check[T](a: Array[T]) = {
  a match {
    case x if x.isInstanceOf[Array[Int]] => println("int")
    case y if y.isInstanceOf[Array[Float]]  => println("float")
    case _ => println("some other type")
  }
}

这里有一个 cheap-trick 可能适合您:

  def check[T](a: Array[T]) = {
    a.headOption match {
      case Some(_:Int) => "Int"
      case Some(_:Float) => "Float"
      case None => "None"
    }
  }

这没有使用任何反射。用 compile-time 反射:

def check2[T: ClassTag](a: Array[T]) = {
    import scala.reflect._
    val e = implicitly[ClassTag[T]]
    e match {
      case x if x == classTag[Int] => "Int"
      case y if y == classTag[Float] => "Float"
    }
  }