-1

I am trying to get a better handle on understanding methods parameterized by types and have this piece of code -

 def inferType[T, U](x: T, y: U): Unit = y match {
    case _: T => println("T")
    case _    => println("Not T")
  }
 inferType("0", 11) // call 1
 inferType(0, 11)   // call 2

I would have expected call 1 to have printed "Not T" and call 2 to have printed "T". However, its printing "T" in both cases. Obviously I am missing something here. Can someone help me with why pattern matching is not matching the generic type T here?

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
Jai Prabhu
  • 245
  • 3
  • 10

1 Answers1

2

The JVM is performing type-erasure, so at runtime all generic types are actually Object, and your match is checking whether y is of type T = Object, which it is.

You can get around this using TypeTag, but this is an anti-pattern in most cases.

francoisr
  • 4,407
  • 1
  • 28
  • 48