开发者

matching types in scala

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 th开发者_运维技巧at, unfortunately.


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜