Scala 中的匹配类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5331095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
matching types in scala
提问by Aaron Yodaiken
Is it possible to match types in Scala? Something like this:
是否可以在 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!"
}
(But that compiles, obviously :))
(但显然可以编译:))
Or perhaps the right approach is type overloading…is that possible?
或者也许正确的方法是类型重载……这可能吗?
I cannot pass it an instance of an object and pattern match on that, unfortunately.
不幸的是,我无法将对象和模式匹配的实例传递给它。
回答by IttayD
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!"
}
回答by Moritz
You can use manifests and do a pattern match on them. The case when passing an array class is problematic though, as the JVM uses a different class for each array type. To work around this issue you can check if the type in question is erased to an array class:
您可以使用清单并对它们进行模式匹配。但是,传递数组类的情况是有问题的,因为 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!"
}
回答by tharindu_DG
Manifestid deprecated. But you can use TypeTag
Manifestid 已弃用。但是你可以使用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.
希望这可以帮助。

