【问题标题】:matching types in scalascala中的匹配类型
【发布时间】:2011-07-16 21:49:52
【问题描述】:

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

(但显然可以编译:))

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

很遗憾,我无法将对象的实例和模式匹配传递给它。

【问题讨论】:

    标签: scala types


    【解决方案1】:
    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!"
    }
    

    【讨论】:

    • 我无法将对象的实例传递给它。
    • 要传递对象的实例,请将冒号前的下划线替换为变量名。例如:case s: String => "you gave me String " + s
    • 我的意思是我需要在没有对象实例的情况下调用它,例如apply[String],而不是apply("string")
    【解决方案2】:

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

    【讨论】:

    【解决方案3】:

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

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2017-02-25
      • 2011-08-25
      • 2013-12-21
      • 1970-01-01
      • 2013-01-11
      • 2012-08-27
      • 2016-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多