【问题标题】:Scala: How to check the type of Array[T]Scala:如何检查 Array[T] 的类型
【发布时间】:2023-04-02 14:14:01
【问题描述】:

我有一个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()

【问题讨论】:

  • 你使用什么版本的 Scala?
  • @texasbruce 2.11.11
  • 为什么需要这样做?
  • @LuisMiguelMejíaSuárez 如前所述,我需要根据不同的Array[T]创建不同的对象
  • 相信编译器,而不是 IDE

标签: scala generics pattern-matching


【解决方案1】:

这是一个可能对您有用的廉价技巧:

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

【讨论】:

    【解决方案2】:

    这对我有用:

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

    【讨论】:

      猜你喜欢
      • 2014-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-07
      • 2022-10-24
      • 2016-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多