scala 中的匹配类型

发布于 2024-10-23 22:07:25 字数 315 浏览 1 评论 0原文

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

但是显然可以编译:))

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

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

Is it possible to match types in Scala? Something like this:

  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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

み青杉依旧 2024-10-30 22:07:25
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!"
}
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!"
}
荒芜了季节 2024-10-30 22:07:25

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

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:

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!"
}
水溶 2024-10-30 22:07:25

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

希望这会有所帮助。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文