When the Scala compiler compiles the previous code, it erases the parameterized type information from the previous code and so it doesn't have the necessary knowledge at runtime; the list we passed does not take any further information about itself. In other words, all type information for generic types is discarded by the time the code compiled. This phenomenon is termed type erasure. This is the reason our function listOf
didn't work as we expected or, let's say, assumed. That's the same reason you got a warning of unreachable code, because our statically typed language was able to know that the second case will never be executed, and the first case is a kind of catch all in this pattern match. Let's explain this a bit better. Take a look at a few cases where type erasure will be applicable. Imagine you have a trait named Tfoo
:
trait Tfoo[T]{ val member: T }
After the process of compilation, the generic type gets converted to object and becomes like the following:
trait...