Search code examples
scalaparameterized

Why does the following parameterized method not compile?


From the Scala API, I got the following example, which does not compile;

scala> def arr[T] = new Array[T](0)
<console>:10: error: cannot find class manifest for element type T
       def arr[T] = new Array[T](0)
                    ^

I was wondering, why it does not compile (the Scala API does not explain the error) ? Isn't it just a normal parameterized method ? Why does the compiler complain about it ?


Solution

  • As the compiler error message says, you need a Manifest constraint.

    scala> def arr[T : Manifest] = new Array[T](0)
    arr: [T](implicit evidence$1: Manifest[T])Array[T]
    

    Learn more about this here. See the paper for more in-depth information.