在scala中匹配类型

时间:2011-03-16 20:02:34

标签: scala types

是否可以匹配Scala中的类型?像这样:

  def apply[T] = T match {
    case String => "you gave me a String",
    case Array  => "you gave me an Array"
    case _ => "I don't know what type that is!"
  }

(但是,编译,显然:))

或许正确的方法是类型重载......这可能吗?

不幸的是,我无法传递一个对象和模式匹配的实例。

3 个答案:

答案 0 :(得分:23)

def apply[T](t: T) = t match {
  case _: String => "you gave me a String"
  case _: Array[_]  => "you gave me an Array"
  case _ => "I don't know what type that is!"
}

答案 1 :(得分:21)

您可以使用清单并对其进行模式匹配。传递数组类的情况虽然有问题,因为JVM对每种数组类型使用不同的类。要解决此问题,您可以检查相关类型是否已擦除到数组类:

val StringManifest = manifest[String]

def apply[T : Manifest] = manifest[T] match {
  case StringManifest => "you gave me a String"
  case x if x.erasure.isArray => "you gave me an Array"
  case _ => "I don't know what type that is!"
}

答案 2 :(得分:6)

Manifest id deprecated. But you can use TypeTag

import scala.reflect.runtime.universe._

def fn[R](r: R)(implicit tag: TypeTag[R]) {

  typeOf(tag) match {
       case t if t =:= typeOf[String] => "you gave me a String"
       case t if t =:= typeOf[Array[_]] => "you gave me an Array"
       case _ => "I don't know what type that is!"
  }
}

Hope this helps.