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.
Language. Pattern matching is a mechanism for checking a value against a pattern. A successful match can also deconstruct a value into its constituent parts. It is a more powerful version of the switch statement in Java and it can likewise be used in place of a series of if/else statements.
Pattern matching is the second most widely used feature of Scala, after function values and closures. Scala provides great support for pattern matching, in processing the messages. A pattern match includes a sequence of alternatives, each starting with the keyword case.
The pattern is a general description of the format of the string. It can consist of text or the special characters X, A, and N preceded by an integer used as a repeating factor. X stands for any characters, A stands for any alphabetic characters, and N stands for any numeric characters.
case _ => does not check for the type, so it would match anything (similar to default in Java). case _ : ByteType matches only an instance of ByteType . It is the same like case x : ByteType , just without binding the casted matched object to a name x .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With