1

I have a class Operator[T: TypeTag : ClassTag] and in of it's methods, I want to use Scala's pattern matching on the parameterized type T. I know how pattern matching works and so tried the following in Scala's repl and got an error.

scala> def matchTest() = T match {
     | case x: String => "abcd"
     | case _ => null
     | }
<console>:11: error: not found: value T
       def matchTest() = T match {
                            ^
Kamal Banga
  • 107
  • 1
  • 10

1 Answers1

5

T is a type, not a value. You can only match on values.

You can get an implicitly[ClassTag[T]] or implicitly[TypeTag[T]], which are values, and do matching on those.

Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
  • 1
    And `classTag[T]` and `typeTag[T]` are shorthands for these. :) –  Jan 02 '15 at 08:16
  • Can you give me full example, I still get some error on doing `def matchTest[T: TypeTag: ClassTag]() = typeTag[T] match { case typeTag[String] => "abcd" case _ => null }` – Kamal Banga Jan 02 '15 at 08:42
  • @KamalBanga Because you can call functions on a case matching. Assign `typeTag[String]` to a variable first, and then match on that. – Daniel C. Sobral Jan 03 '15 at 23:50