Scala arrays and parameterized types

I am trying to define a generic class that accepts a parameterized type T, and then use the type in the Array definition in the class. I wrote the following, which I thought seemed to work

class MyClass[T] { val myarr:Array[T] = new Array[T](10) } 

But the compiler complains about the following

  • cannot find class manifest for element type T
  • NewArray is not a member of Null

Does anyone know what is happening here and what does not please him?

+4
source share
1 answer

The compiler must know how to create instances of type T. In the traditional Java method of handling generics using type erase, this cannot be done intelligently; the compiler simply says, β€œHey, I don’t know what T is, so I don’t feel so good that I let you instantiate T.” In Scala, however, there is a word for this: manifestos. To enable the manifest for T, simply change the first line of this code to

 class MyClass[T : Manifest] { 

What is it.

+9
source

Source: https://habr.com/ru/post/1390755/


All Articles