繁体   English   中英

在Scala中匹配类型

[英]matching types in scala

是否可以在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!"
  }

(但是编译,很明显:))

也许正确的方法是类型重载……可能吗?

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

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

您可以使用清单并对其进行模式匹配。 但是,传递数组类的情况是有问题的,因为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!"
}

Manifest ID已弃用。 但是你可以使用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!"
  }
}

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM