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

问题描述

我有一个[ 0.10509459 -0.31389323 0. 0. 0. ],如何检查它的类型?

我尝试过

Array[T]

编译器引发错误

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

我要这样做的原因是,假设我能够枚举所有类型,并且目前只有Int和Float

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

解决方法

这对我有用:

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

这是一个便宜的技巧,可能对您有用:

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

这没有任何反射。使用编译时反射:

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